I have problem with putting in the right parameters from an eventListener into a function.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var image = galleryContainer.getElementsByTagName('div');
//console.log(image);
var images = new Array();
images.push(image);
for(var i = 0; i < images[0].length; i++) {
images[0][i].addEventListener('click', function() {showImage(this)
}, false);
};
}
// I dont know with parameter to put into showImage() from the listener.
function showImage( here is the problem ) {
var preview = document.getElementById('preview');
preview.innerhtml = image.innerhtml;
// I want to put the image into the preview element.
}
</script>
</head>
<body>
<div id="galleryContainer">
<div>trams</div>
<div>trams</div>
<div>trams</div>
<div>trams</div>
</div>
<div id="preview" style="width: 200px; height: 200px; border: 1px solid red"></div>
</body>
Try this code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var images = galleryContainer.getElementsByTagName('div');
//console.log(images);
for(var i = 0; i < images.length; i++) {
images[i].addEventListener('click', showImage, false);
};
}
// I dont know with parameter to put into showImage() from the listener.
function showImage(ev) {
ev=ev||event; // ev now point to click event object
var preview = document.getElementById('preview');
preview.innerHTML = this.innerHTML; // this point to DIV(trams)
}
</script>
</head>
<body>
<div id="galleryContainer">
<div>trams1</div>
<div>trams2</div>
<div>trams3</div>
<div>trams4</div>
</div>
<div id="preview" style="width: 200px; height: 200px; border: 1px solid red"></div>
</body>
Working example http://jsfiddle.net/Cp6HJ/
window.onload = function() {
var galleryContainer = document.getElementById('galleryContainer');
var image = galleryContainer.getElementsByTagName('div');
//console.log(image);
var images = new Array();
images.push(image);
for(var i = 0; i < images[0].length; i++) {
var callback = function(item){ return function(){ showImage(item); }; }(images[0][i]);
images[0][i].addEventListener('click', callback, false);
};
};
function showImage( item ) {
var preview = document.getElementById('preview');
preview.innerHTML = item.innerHTML;
}
Use this for the function definition statement :
function showImage(image) {
...
}
And correction in the inner html statement:
(note the capitalized 'H')
preview.innerHTML = image.innerHTML;
Related
I am working on a memory game and I asked a previous question earlier which was answered. I've had this problem and I haven't been able to find a solution with effort. So it's a memory game and when the cards are clicked, they are pushed into an array which can hold two elements at max (you can only click two cards) and then the two elements' frontSrc is checked if they are the same. I set that using an expando property. If so, have them visible and then clear the array so I can do more comparisons. However, it doesn't seem to be working as intended. I'll attach a video below. I've tried using timeout to set the length again, but that didn't work. It works for the first cards, but the other ones after that, it doesn't work.
Here is my code.
<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
Click nbfs://nbhost/SystemFileSystem/Templates/Other/html.html to edit this template
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.card{
width: 35%;
}
#cards{
display: grid;
grid-template-columns:25% 25% 25% 25%;
row-gap: 25px;
}
</style>
</head>
<body onload="init()">
<section id="cards">
</section>
<script>
var arrCards = [];
var arrShowedCards = [];
//appendElements();
function init(){
createCards();
shuffleCards();
appendElements();
}
function createCards(){
var arrCardNames = ["Mouse","Penguin","Pop","Mouse","Penguin","Pop"];
for(var i = 0; i<6; i++){
var card = document.createElement("IMG");
card.src = "Images/red_back.png";
card.className = "card";
card.frontSrc = "Images/" + arrCardNames[i] + ".png";
card.id = "card" + i;
card.addEventListener("click", showCard);
document.getElementById("cards").appendChild(card);
arrCards.push(card);
}
}
function shuffleCards(){
for (let i = arrCards.length-1; i > 0; i--)
{
const j = Math.floor(Math.random() * (i + 1));
const temp = arrCards[i];
arrCards[i] = arrCards[j];
arrCards[j] = temp;
}
return arrCards;
}
function appendElements(){
for(var i = 0; i<arrCards.length; i++){
document.getElementById("cards").appendChild(arrCards[i]);
}
}
function showCard(){
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if(arrShowedCards.length === 2){
if(arrShowedCards[0].frontSrc === arrShowedCards[1].frontSrc){
console.log("Match!");
arrShowedCards = [];
}
else{
console.log("No match!");
setTimeout(function(){
arrShowedCards[0].src = sourceString;
arrShowedCards[1].src = sourceString;
}, 1000);
}
}
}
</script>
</body>
</html>
I am not sure how come it doesn't work for it for the other cards.
Here is the video.
https://drive.google.com/file/d/1aRPfLALHvTKjawGaiRgD1d0hWQT3BPDQ/view
If anyone finds a better way to approach this, let me know.
Thanks!
I think when not match, you need to reset arrShowedCards otherwise its length will be greater than 2 forever.
function showCard() {
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if (arrShowedCards.length === 2) {
var a = arrShowedCards[0], b = arrShowedCards[1];
arrShowedCards.length = 0;
if (a.frontSrc === b.frontSrc) {
console.log("Match!");
} else {
console.log("No match!");
setTimeout(function () {
a.src = sourceString;
b.src = sourceString;
}, 1000);
}
}
}
I build a small application to switch between random images in an iframe, I would like that after 10 or 20 images the user will get an image or source I want him to get and not a random one, and then return to the loop.
I have a problem with the count and if function, will appreciate any help. Thanks
<body>
<iframe id="img_main" src="https://www.example.com/img_4.jpg" width="600" height="800" frameborder="1" scrolling="no"></iframe>
<br>
<button id="H" type="button" onclick=(newImg(),clickCounter(),changeImg())>images</button>
<div id="result"></div>
<script>
function newImg(){
var myArray = [
"img_1.jpg",
"img_2.jpg",
"img_3.jpg",
"img_4.jpg"
];
var imgNew = "https://example.com/"
var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
document.getElementById("img_main").src = "https://example.com/" + randomItem ;
}
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
function changeImg(){
if (localStorage.clickcount = 10,20) {
document.getElementById("ins_main").src = "https://example.com/pre_defined_img.jpg";
}
}
</script>
</body>
the way I see that...
by simply use of the modulo (finds the remainder after division)
you don't need to use an iframe, img element is enough.
use an IIFE. as closure method
file : "myScript.js"
const imgBox = (function()
{
const refURL = 'https://i.picsum.photos/id/'
, imgName = [ '251/300/500.jpg', '252/300/500.jpg', '253/300/500.jpg', '254/300/500.jpg'
, '255/300/500.jpg', '256/300/500.jpg', '257/300/500.jpg', '258/300/500.jpg'
, '259/300/500.jpg', '260/300/500.jpg', '261/300/500.jpg', '146/300/500.jpg'
, '263/300/500.jpg', '264/300/500.jpg', '265/300/500.jpg', '266/300/500.jpg'
, '267/300/500.jpg', '268/300/500.jpg', '269/300/500.jpg', '270/300/500.jpg'
, '271/300/500.jpg', '272/300/500.jpg', '273/300/500.jpg', '274/300/500.jpg'
]
, imgZero = '250/300/500.jpg'
, imgSiz = imgName.length
, imgMain = document.getElementById('img-main')
;
var imgNum = 0, randomI = 0;
const obj =
{ setNext()
{
if (!(++imgNum % 10)) // each 10 times
{
imgMain.src = refURL + imgZero
}
else
{
randomI = Math.floor(Math.random() * imgSiz)
imgMain.src = refURL + imgName[randomI]
}
return imgNum
}
}
return obj
})()
const btImg = document.getElementById('bt-img')
, imgCount = document.getElementById('img-count')
, banner = document.getElementById('my-banner')
;
btImg.onclick =evt=>
{
let counter = imgBox.setNext()
imgCount.textContent = counter
if (!(counter %50)) // each 50 times..
{
changeBanner()
}
}
// changing banner function...
function changeBanner()
{
//.....
// do what ever you want to change your banner
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
img#img-main {
width: 300px;
height: 500px;
border: 1px solid grey;
padding: 2px;
}
</style>
</head>
<body>
<img id="img-main" src="https://i.picsum.photos/id/250/300/500.jpg" alt="" >
<p id="img-count">0</p>
<button id="bt-img">Image change</button>
<div id="my-banner">the banner</div>
<script src="myScript.js"></script>
</body>
</html>
I can only let the user upload a certain amount of pictures so I am trying to increment a variable 'j' three times before disabling the upload picture button. I know j is incrementing because I printed it out in an alert box for each increment. I really want to know how this is not working. if you have a more elegant solution I am happy with that too.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<input id="browse" type="file" onchange="previewFiles()" multiple>
<div id="preview"></div>
<script>
var j = 0;
if (j < 3){
function previewFiles() {
j++;
alert(j);
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild( image );
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
}
}
else {
alert("I want to get in here");
document.getElementById("browse").disabled = true;
}
</script>
</body>
The if block is outside of your function, so when previewFiles is called, the if block is not executed. Try this:
var j = 0;
function previewFiles() {
if (j < 3) {
j++;
alert(j);
var preview = document.querySelector('#preview');
var files = document.querySelector('input[type=file]').files;
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
}, false);
reader.readAsDataURL(file);
}
}
if (files) {
[].forEach.call(files, readAndPreview);
}
} else {
alert("I want to get in here");
document.getElementById("browse").disabled = true;
}
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<input id="browse" type="file" onchange="previewFiles()" multiple>
<div id="preview"></div>
</body>
In a html page with mathematical formulas using MathJax, I'm trying a smooth transition in the change from one formula to the another.
Here is the current code, that you can test here
<!DOCTYPE html>
<html>
<head>
<!-- https://jsfiddle.net/LnfL020r/2 -->
<title>math guided training</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
Macros: {
mgtMult: "",
mgtSelect: [ "\\bbox[10px,border:1px solid red]{#1}", 1],
}
}
});
</script>
<script type="text/javascript"
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<style>
.results {
display: flex;
height: 4cm;
position: relative;
}
#fadeBox,
#visibleBox {
width: 100%;
height: 100%;
position: absolute;
top: 0%;
left: 0;
}
</style>
</head>
<body>
<script>
var QUEUE = MathJax.Hub.queue; // shorthand for the queue
var math = null; // the jax element
var box = null; // the box math is in
var formula = "1+2x^3";
var SHOWBOX = function () {
var a = $('#box').html();
var dstDiv = $('#visibleBox');
dstDiv.html(a);
}
var SHOWBOX_FADE = function () {
var a = $('#box').html();
var dstDiv = $('#visibleBox');
var fadeDiv = $('#fadeBox');
fadeDiv.html(a);
fadeDiv.fadeIn(2000,function() {
dstDiv.html(a);
fadeDiv.hide();
});
}
var REFRESH = function () {
QUEUE.Push(
["Text",math,formula], // == math.Text(formula), [ method, object, args... ]
SHOWBOX
);
}
var REFRESH_FADE = function () {
QUEUE.Push(
["Text",math,formula], // [ method, object, args... ]
SHOWBOX_FADE
);
}
// Get the element jax when MathJax has produced it.
QUEUE.Push(
function () {
math = MathJax.Hub.getAllJax("box")[0]; // returns a MathJax.ElementJax
math.Text(formula);
SHOWBOX();
}
);
setTimeout(function(){
SHOWBOX();
}, 2000);
window.changeIt = function() {
formula = "1 + 2 { \\left( y + 4 \\right) } ^ 3 ";
REFRESH_FADE();
}
</script>
</head>
<body>
<div id="box" style="visibility:hidden; font-size: 500%; height:1px;">
\( \)
</div>
<div class="results">
<div id="visibleBox" style="font-size: 500%;">
Loading ...
</div>
<div id="fadeBox" style="font-size: 500%; display:none;">
</div>
</div>
<button onclick='changeIt()'/>click me</button>
</body>
</html>
The problem is:
The second formula has different height than the first one, due to the parenthesis. For this reason, the common part "1 + " of the second one is printed slightly down respect to its print in the first formula.
That produces an effect of borrow during the transition. I want that the "1 + " part, common to both formulas, doesn't moves when changing from first to second.
Any hint?
maybe this will work :
var SHOWBOX = function () {
var a = $('#box').html();
var dstDiv = $('#visibleBox');
// apply margin for the first equation
dstDiv.css({"margin-top":"2px"});
dstDiv.html(a);
}
var SHOWBOX_FADE = function () {
var a = $('#box').html();
var dstDiv = $('#visibleBox');
var fadeDiv = $('#fadeBox');
fadeDiv.html(a).fadeOut();
fadeDiv.fadeIn(500,function() {
dstDiv.html(a);
// remove the margin for the second equation
dstDiv.css({"margin-top":"0"});
fadeDiv.hide();
});
}
just applying a margin to counter the slight variance in top margin
Made little change in fadeIn and fadeOut
fadeDiv.html(a);
dstDiv.fadeOut(1000,function() {
dstDiv.html(a);
fadeDiv.fadeIn(1000);
});
}
Forked fiddle
Please comment if transition is not up to expection
EDIT
Updated With requirement
Fiddle link
window.onload=function(){
var QUEUE = MathJax.Hub.queue; // shorthand for the queue
var math = null; // the jax element
var mathdef = null; // the jax element
var box = null; // the box math is in
var defaultformula = "1+";
var formula = "2x^2";
var SHOWBOX = function () {
var a = $('#box').html();
var def = $('#defbox').html();
var fixedDiv = $('#fixed');
fixedDiv.html(def);
var dstDiv = $('#visibleBox');
dstDiv.html(a);
}
var SHOWBOX_FADE = function () {
var a = $('#box').html();
var dstDiv = $('#visibleBox');
var fadeDiv = $('#fadeBox');
fadeDiv.html(a);
dstDiv.fadeOut(1000,function() {
dstDiv.html(a);
fadeDiv.fadeIn(1000);
});
}
var REFRESH = function () {
QUEUE.Push(
["Text",math,formula], // == math.Text(formula), [ method, object, args... ]
SHOWBOX
);
QUEUE.Push(
["Text",mathdef,defaultformula], // == math.Text(formula), [ method, object, args... ]
SHOWBOX
);
}
var REFRESH_FADE = function () {
QUEUE.Push(
["Text",math,formula], // [ method, object, args... ]
SHOWBOX_FADE
);
}
// Get the element jax when MathJax has produced it.
QUEUE.Push(
function () {
math = MathJax.Hub.getAllJax("box")[0]; // returns a MathJax.ElementJax
mathdef = MathJax.Hub.getAllJax("defbox")[0]; // returns a MathJax.ElementJax
mathdef.Text(defaultformula);
math.Text(formula);
SHOWBOX();
}
);
setTimeout(function(){
SHOWBOX();
}, 2000);
window.changeIt = function() {
formula = "2 { \\left( y + 4 \\right) } ^ 2";
REFRESH_FADE();
}
}//]]>
.results {
display: flex;
height: 4cm;
position: relative;
}
#fadeBox,
#visibleBox {
width: 100%;
height: 100%;
position: absolute;
top: 0%;
left: 0;
}
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
Macros: {
mgtMult: "",
mgtSelect: [ "\\bbox[10px,border:1px solid red]{#1}", 1],
},
Macros: {
mgtMult: "",
mgtSelect: [ "\\bdefbox[10px,border:1px solid red]{#1}", 1],
}
}
});
</script>
<script type="text/javascript"
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<div id="defbox" style="visibility:hidden; font-size: 500%; height:1px;padding-top:10px">
\( \)
</div>
<div id="box" style="visibility:hidden; font-size: 500%; height:1px;padding-left:200px">
\( \)
</div>
<div class="results">
<div id="fixed" style="font-size: 500%;margin-top:50x">
Loading ...
</div>
<div id="visibleBox" style="font-size: 500%;padding-left:100px">
</div>
<div id="fadeBox" style="font-size: 500%; display:none;padding-left:100px">
</div>
</div>
<button onclick='changeIt()'>click me</button>
</body>
</html>
When I run it, the 1st image appears and after one second all I could see is a white blank screen. Nothing happens. I guess there's a problem in JavaScript code.
Here's the code I tried..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
img {
width: 582px;
height: 306px;
}
</style>
</head>
<body>
<img src="image-slider-1.jpg" id="myphoto" />
<script type="text/javascript">
var image=document.getElementById("myphoto");
var imageArray=("image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg");
var imageIndex=0;
function slide(){
image.setAttribute("src",imageArray [imageIndex] );
imageIndex++;
if(imageIndex>=imageArray.length) {
imageIndex=0;
}
}
setInterval(slide,1000);
</script>
</body>
</html>
Any help is greatly appreciated.
Try this. It worked for me.
var speed = 3700; //interval
var Pic = new Array();
Pic[0] = 'abc.jpg';
Pic[1] = 'def.jpg';
Pic[2] = 'ghi.jpg';
//add as many as you want
var t; //interval
var j = 0;
var p = Pic.length;
var preLoad = new Array()
for (i = 0; i < p; i++)
{
preLoad[i] = new Image();
preLoad[i].src = Pic[i];
}
// call this from your html as shown below
//<body onload="runBGSlideShow()">
function runBGSlideShow(){
if (document.body)
{
document.body.background = Pic[j];
j = j + 1;
if (j > (p-1))
{
j=0; //start from pic1 again
}
t = setTimeout('runBGSlideShow()', speed);
}
}
The following line is not doing what you expect:
var imageArray=("image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg");
if you check the value of imageArray after this call, you will find just a string, containing "image-slider-5.jpg". (Why? See the workings of the comma operator in javascript.)
To properly declare an array of strings, use the [] notation:
var imageArray=["image-slider-1.jpg","image-slider-2.jpg","image-slider-3.jpg","image-slider-4.jpg","image-slider-5.jpg"];