javascript: image change for certain times - javascript

I found this script :
<html>
<head>
<script type="text/javascript">
var paths = ['assets/img/head.png','assets/img/tail.png'];
var curPic = 1;
var imgO = new Array();
for(i=0; i < paths.length; i++) {
imgO[i] = new Image();
imgO[i].src = paths[i];
}
function swapImage() {
curPic = (++curPic > paths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
setTimeout(swapImage,200);
}
window.onload=function() {
imgCont = document.getElementById('img');
swapImage();
}
</script>
</head>
<body>
<div>
<img id="img"/>
</div>
</body>
</html>
this repeate changing the pictures for unlimited time, but how do I change this that it repeats for e.g. 5 times only ?

Just use a tracker variable.
var to, times = 0; //<-- init the tracker, and a var for the timeout
function swapImage() {
if (times == 5) {
clearTimeout(to); //<-- if already 5 times, cancel timeout and...
return; //<-- ...quit
}
curPic = (++curPic > paths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
to = setTimeout(swapImage,200); //<-- make the TO accessible via our var
times++;
}

Related

How to check if a tag has image in it using Vanilla Javascript?

var squares = document.querySelectorAll('td');
var img1 = document.createElement("img");
img1.src = "Group 1.svg";
var img2 = document.createElement('img');
img2.src = "Ellipse 1.svg";
function changeMarker() {
if (this.textContent == '') {
this.appendChild(img1);
} else if (childElements[this].localName != null) {
this.appendChild(img2);
} else {
this.textContent = '';
}
}
for (var i = 0; i < squares.length; i++) {
squares[i].childNode.addEventListener('click', changeMarker);
}
The method .getElementsByTagName is available for you to use. Since we get the container first then call that element's copy of this method, we just look inside it and ignore the rest of the document.
<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt)
{
let d1 = byId('div1');
let d2 = byId('div2');
let imgCount1 = d1.getElementsByTagName('img').length;
let imgCount2 = d2.getElementsByTagName('img').length;
d1.textContent += ` - Img Count: ${imgCount1}`;
d2.textContent += ` - Img Count: ${imgCount2}`;
}
</script>
</head>
<body>
<div id='div1'>No image</div>
<div id='div2'>2 images<img><img></div>
<img><img><img>
</body>
</html>

How do I cycle through pictures in JavaScript?

My html:
<img src="C:\Users\Shady\Downloads\restaurant\food1.jpg" alt="rotating image" width="400" height="300" id="rotator">
My Javascript:
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 5;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
Everything makes sense to me but for some reason it is not working. It is only showing the first picture (doesn't cycle through the pictures). Please let me know if you need anything else. Thank you.
you are getting element 'rotator' before document is loaded so it doesn't exist.
Try this:
function start() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 1;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
};
window.onload=function(){
start();
}
Preload the images:
<script type="text/javascript">
var slideimages = new Array() // create new array to preload images
slideimages[0] = new Image() // create new instance of image object
slideimages[0].src = "firstcar.gif" // set image src property to image path, preloading image in the process
slideimages[1] = new Image()
slideimages[1].src = "secondcar.gif"
slideimages[2] = new Image()
slideimages[2].src = "thirdcar.gif"
</script>
Display the first image:
<img src="firstcar.gif" id="slide" width="100" height="56" />
Create the slideshow(cycle):
<script type="text/javascript">
//variable that will increment through the images
var step=0
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.getElementById('slide').src = slideimages[step].src
if (step<2)
step++
else
step=0
//call function "slideit()" every 2.5 seconds
setTimeout("slideit()",2500)
}
slideit()
</script>
This is how you can try...it works fine for me....
<html>
<body>
<img src="file:///C:/Users/Public/Pictures/Sample%20Pictures/test1 (2).jpg" alt="rotating image" width="400" height="300" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');
var imageDir = 'file:///C:/Users/Public/Pictures/Sample%20Pictures/';
var delayInSeconds = 5;
var images = ['test1.jpg', 'test1 (2).jpg', 'test1 (3).jpg', 'test1 (4).jpg', 'test1 (5).jpg', 'test1 (6).jpg', 'test1 (7).jpg', 'test1 (8).jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 100);
})();
</script>
</body>
</html>
You try to access the DOM element with the id rotator before it got loaded.
There are two ways to bypass this problem:
You can move your script tag below the img tag, because then the javascript get's execute after the img element has been loaded:
<img src="C:\Users\Shady\Downloads\restaurant\food1.jpg" alt="rotating image" width="400" height="300" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 5;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
You can set the onload event handler for the document to your anonymous function (or give it a name if you like):
<script type="text/javascript">
window.onload = function() {
var rotator = document.getElementById('rotator');
var imageDir = 'C:\\Users\\Shady\\Downloads\\restaurant\\';
var delayInSeconds = 5;
var images = ['food1.jpg', 'food2.jpg', 'food3.jpg', 'food4.jpg', 'food5.jpg', 'food6.jpg', 'food7.jpg', 'food8.jpg'];
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
};
</script>

How to display innerHTML values one by one javascript

Trying to display the values of my inner HTML, from 10 to 1, but am able to show only the value 1.
the values should display, one by one..
For example if 10 get displays, it should hide and then 9 should display,
it just like a timer.
How to fix this, this is what I have tried.
HTML:
<div id='test'></div>
JS:
var a = 10;
var b=1;
var tar = document.getElementById('test');
for(var a=10;a>=b;a--){
tar.innerHTML = a;
if(a==b){
tar.innerHTML = a;
//tar.style.display='none';
window.location.href = "http://www.google.co.in";
}
}
fiddle demo
The problem you have is that JavaScript can execute incredibly fast, so it is counting from 10 to 1 faster than you can see. You need to slow it down a little with a timer...
In this example, there is a one second delay between each number.
var a = 10;
var b = 1;
var tar = document.getElementById('test');
var timer;
function countDown() {
tar.innerHTML = a;
if(a === b) {
tar.innerHTML = a;
//tar.style.display = 'none';
window.location.href = "http://www.google.co.in";
} else {
a--;
timer = window.setTimeout(countDown, 1000);
}
}
countDown();
<html>
<head>
<script>
var myVar = setInterval(function(){myTimer()}, 1000);
var i=10;
function myTimer() {
i--;
if(i==1)
clearInterval(myVar);
document.getElementById("test").innerHTML = i;
}
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
You can simply do:
var counter = 10; // number of iterations
var tar = document.getElementById('test');
var interval = setInterval(function(){
if (counter === 0) clearInterval(interval); // skip if reached end
tar.innerHTML = counter; // update html
counter--; // update counter value
}, 1000) // 1000 = 1 second
See Fiddle
http://jsfiddle.net/0sbu5f8c/13/
var a = 10;
var b = 1;
var tar = document.getElementById('test');
var timer = setInterval(function () {
tar.innerHTML = a;
if(a === b) {
window.clearInterval(timer);
//window.location.href = "http://www.google.co.in";
}
a -= 1;
}, 500);

Txt doesn`t appear on the stage

Can someone pls tell me what I am doing wrong. I am trying to add text to my stage but the stage doesn`t show any text and there are no errors given. Did I do something wrong. I am adding the txt with addChild so it should appear? why is it not showing anything, it is not because of the color because I changed the color of the text.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>game</title>
<script type="text/javascript" src="game.js"></script>
<script type="text/javascript" src="js/easel.js"></script>
</head>
<body onload="init();">
<canvas id=canvas width="960" height="580"></canvas>
</body>
</html>
javascript:
var canvas;
var stage;
var score;
var bitmap;
var bmpList;
var txt;
var play;
function init() {
canvas = document.getElementById("canvas");
stage = new Stage(canvas);
score = 0;
var image = new Image();
image.src = "imgs/stone.png";
image.onload = maakTegenstander;
}
function maakTegenstander(event){
var image = event.target;
var container = new Container();
stage.addChild(container);
var l = 5;
bmpList=[]; // dit is een array
for(var i=0; i<l; i++){
bitmap = new Bitmap(image);
container.addChild(bitmap);
bitmap.name="stone"+i;
verwijderTegenstander(bitmap);
bitmap.regX = bitmap.image.width/2|0;
bitmap.regY = bitmap.image.height/2|0;
bitmap.mouseEnabled = true;
bmpList.push(bitmap);
}
txt = new Text ("Score: 0", "24px Arial", "#333");
txt.textBaseline="top";
txt.x = 400;
txt.y = 20;
stage.addChild(txt);
play=true;
Ticker.addListener(window);
}
function verwijderTegenstander(stone){
stone.y = canvas.height - 700;
stone.x = canvas.width* Math.random() + 30;
stone.speed = (Math.random()*5)+2;
}
function tick(){
if(play == true){
var l=bmpList.length;
}
if (play == true){
var l = bmpList.length;
for(var i=0; i<l; i++){
var bmp = bmpList[i];
if (bmp.y < 650){
bmp.y += bmp.speed;
}else{
//gameOver();
console.log("game over");
}
}
}
txt.text = "Punten: "+score;
stage.update();
}
Here's a fiddle based on your code: http://jsfiddle.net/fXgeg/1/
I've changed two things:
For every call to easeljs module, I've added 'createjs.' e.g.
createjs.Stage
I've changed the ticker listener registration like this:
//Ticker.addListener(window); <- this is wrong
createjs.Ticker.addEventListener("tick", tick);
This way you provide the event type - "tick" and the function which should be called every time this event occurs - tick()

javascript clear timeouts in loop

The code below appends numbers in sequence from 1 to 10 when the start button is clicked. I'd like to use clearTimeout to cancel the operation when the stop button is clicked.
It seems to me that a dynamic variable must be created (where x is currently assigned the doSetTimeout function), but I have not yet found a way to do so. Any suggestions?
Thanks!
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function doSetTimeout(func, func_param, time) {
setTimeout(function(){func(func_param);}, time);
}
function createNode(base) {
var node = document.createElement("p");
var writeI = base + "";
var textnode = document.createTextNode(writeI);
node.appendChild(textnode);
document.body.appendChild(node);
}
$(document).ready(function() {
$("#start").click(function() {
for (var i = 1; i <= 10; i++) {
var time = i*1000;
var x = doSetTimeout(createNode, i, time);
}
});
});
</script>
</head>
<body>
<button id="start">Start</button>
<button id="stop">Stop</button>
</body>
Get the return value of setTimeout, keep it in a list, and clear it when you click stop.
function doSetTimeout(func, func_param, time) {
return setTimeout(function(){func(func_param);}, time);
}
$(document).ready(function() {
var timeouts = [];
$("#start").click(function() {
for (var i = 1; i <= 10; i++) {
var time = i*1000;
timeouts.push(doSetTimeout(createNode, i, time));
}
});
$("#stop").click(function () {
for (var i = 0; i <= timeouts.length; i += 1) {
clearTimeout(timeouts[i]);
}
});
});
This might also clear timeouts that have already finished, but I doubt that's really very important.

Categories

Resources