autorefreshing an image in HTML with javascript - javascript

I'm writing a webpage and looking to autorefresh an image in my directory every second. I have code written but I'm not sure why its not working.
<html>
<SCRIPT language="JavaScript" type="text/javascript">
var t = 1 // Interval in Seconds
images = new Array('foo.png'); //URLs of the Images
function Start() {
tmp = new Date();
tmp = "?"+tmp.getTime();
for (i=1;i<image.length;i++){
document.getElementById("img"+i).src = images[i]+tmp;
}
setTimeout("Start()", t*1000)
}
Start();
</SCRIPT>
<body>
<IMG src="foo.png" border="1" name="refresh" id="img1">
</body>
</html>

The problem is, array index starts from 0 not from 1, your looping variable start with 1, but the array has only 1 item at index 0, so images[1] will return undefined.
var t = 1 // Interval in Seconds
images = new Array('foo.png'); //URLs of the Images
function Start() {
var tmp = "?" + new Date().getTime();
for (var i = 0; i < image.length; i++) {
document.getElementById("img" + (i + 1)).src = images[i] + tmp;
}
setTimeout("Start()", t * 1000)
}
Start();

As mentioned by #Arun P Johny, array index starts with zero.
You used i<image.length in for loop, but your var name is images, Note that extra s.
Since the value of i starts from 0, set id of <img> to img0
<html>
<SCRIPT language="JavaScript" type="text/javascript">
var t = 1 // Interval in Seconds
images = new Array('foo.png'); //URLs of the Images
function Start() {
tmp = new Date();
tmp = "?"+tmp.getTime();
for (i=0;i<images.length;i++){
document.getElementById("img"+i).src = images[i]+tmp;
}
setTimeout(Start, t*1000)
}
Start();
</SCRIPT>
<body>
<IMG src="foo.png" border="1" name="refresh" id="img0">
</body>
</html>

This will refresh real-time any image when an image change has been made.
<script>
setInterval(function(){
$("#logo").each(function(){
var timeStamp = (new Date()).getTime();
$(this).attr("src", $(this).attr("src") + timeStamp );
});
}, 1000);
</script>
This will refresh the div to prevent a long URL from being generated by ?_=' +Math.random()+'.
<script>
$(document).ready(function(){
setInterval(function(){
$("#myDIV").load(window.location.href + " #myDIV" );
}, 80000);
});
</script>
The image.
<div id="myDIV">
<img id="logo" src="logo.png?_=' +Math.random()+'" width="100%" height="auto" alt="onerror="this.onerror=null;this.src="error.png";"/>
</div>

Related

How to make images appear randomly in Javascript?

I need to create a web page with a button that says "start game". When this button is clicked, 5 images I have downloaded (img1.png...img5.png) must appear randomly, one at a time, every half a second. Here is my code so far, any help would be greatly appreciated!
<html>
<head>
<script>
var rollImagesSchedule;
var rollImagesCounter;
function rollImagesAnimation(){
rollImagesCounter = 0;
rollImagesSchedule = setInterval(500);
}
function rollImages(){
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
rollImagesCounter = rollImagesCounter + 1;
if (rollImagesCounter == 10){
clearInterval(rollImagesSchedule);
}
}
</script>
</head>
<body>
<h1>Game</h1>
<button onClick="rollImagesAnimation()">Start frog game</button>
<br /><br />
<img id="display" style='width:200px; height:200px;'>
</body>
</html>
I think you're getting stuck with the way to use setInterval.
You can try to create a counter outside setInterval function, and nest all of your works inside of it. And the counter should be checked at the top.
function rollImages(){
var counter = 0;
var interval = setInterval(function () {
if (counter === 10) {
clearInterval(interval);
return;
}
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
counter++;
}, 500);
}
Then, you can edit the way to catch event rollImages:
<button onClick="rollImages()">Start frog game</button>
My English is not very good, so I might misunderstand your question. Let me answer it according to what I understand.
Your requirement is to randomly display one of the five pictures every 500 milliseconds, right? If so, you can try this idea:
Put the src of 5 pictures into an array
var imageSrcs = ["image1","image2","image3","image4","image5"];
Every 500 milliseconds, execute the following function:
function rollImages(){
// Randomly generate a random number between 0-4
int index = Math.floor(Math.random() * 5) + 1;
var theImage = document.getElementById("display");
// Use random numbers as subscripts and take values from the array
theImage.src = imageSrcs[index];
}
You can store the images name files into an array and then setInterval a random number and assign the source of an img html element:
var list = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
];
var i = 0;
function changeImgs() {
var imageValue = Math.floor(Math.random() * list.length - 1) + 1;
image.src = list[imageValue];
}
setInterval(function() {
changeImgs()
}, 2000);
window.onload = changeImgs;
<img id="image" class="size">

How do I get the slideshow to disappear after one cycle through (javascript)

this intro slideshow works so far, it starts automatically when you load the webpage and cycles through the 4 photos. But I want the slideshow to disappear (to reveal the website homepage underneath) after it has cycled through the 4 photos only once, but need some help how to proceed forward.
<!DOCTYPE html>
<head>
</head>
<body>
<div id="slideshow">
<img id="pic" width="100%" height="auto" alt="Icon" src="one.jpg">
</div>
<script>
var i, imgs, pic;
function rotate() {
pic.src = imgs[i];
(i === (imgs.length - 1)) ? (i = 0) : (i++);
setTimeout(rotate, 1000);
}
function init() {
pic = document.getElementById("pic");
imgs = ["one.jpg", "two.jpg", "three.jpg", "four.jpg"];
var preload = new Array();
for (i = 0; i < imgs.length; i++) {
preload[i] = new Image();
preload[i].src = imgs[i];
}
i = 0;
rotate();
}
document.addEventListener("DOMContentLoaded", init, false);
</script>
</body>
</html>
var count = 0
function rotate() {
pic.src = imgs[i];
(i === (imgs.length - 1)) ? (i = 0) : (i++);
if (count < imgs.length) {
count++;
setTimeout(rotate, 1000);
} else {
document.getElementById("slideshow").style.display = 'none';
}
}
Hi,
you have to count your number of slides. Afterwards just check if you already finished.
greetings
<!DOCTYPE html>
<head>
</head>
<body>
<div id="slideshow">
<img id="pic" width="100%" height="auto" alt="Icon" src="one.jpg">
</div>
<script>
var i, imgs, pic;
function rotate() {
pic.src = imgs[i];
if(i<(imgs.length - 1)){
i++;
setTimeout(rotate, 1000);
}
}
function init() {
pic = document.getElementById("pic");
imgs = ["one.jpg", "two.jpg", "three.jpg", "four.jpg"];
var preload = new Array();
for (i = 0; i < imgs.length; i++) {
preload[i] = new Image();
preload[i].src = imgs[i];
}
i = 0;
rotate();
}
document.addEventListener("DOMContentLoaded", init, false);
</script>
</body>
</html>
if(i<(imgs.length - 1)){
i++;
setTimeout(rotate, 1000);
}
You need to check for how many time the rotate() method need to call.

error on trying to change image in sequence from list JavaScript

I have a list:
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
I made a code which attempts at displaying image1 when the page loads but for ever 3 seconds the image changes to the next image in the list. However when the code was ran it was stuck on image1 and did not change in the next 3 seconds.
This is my JavaScript code so far:
<html>
<body>
<body onload = "myFunction()">
<img src ="image1.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
setTimeout("myFunction", 3000)
}
window.onLoad = function(){
myFunction();
}
</script>
</body>
</html>
I have seen similar codes but the answers answered did not meet my specification.
You can use setInterval (passing a function rather than a string) instead of recursively calling setTimeout. Also note that your counter logic can be greatly simplified with the use of the modulo (%) operator:
<html>
<body>
<img src="image1.png" alt="image1.png" id="target">
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
var target = document.getElementById("target")
setInterval(function myFunction() {
counter = (counter + 1) % images.length
target.src = target.alt = images[counter]
}, 3000)
</script>
</body>
</html>
In setInterval, you need to pass the function myFunction as parameter, not the function name "myFunction":
Change it to this:
setTimeout(myFunction, 3000);
setTimeout - will work only one time
setInterval - will continue always
<html>
<body>
<img src ="logo.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["logo.png", "222.jpg"];
function myFunction() {
counter++;
if (counter > 1) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
function my2(){
setInterval("myFunction()", 1000);
}
window.onload = function(){
my2();
}
</script>
</body>
</html>
Expanding on what others have mentioned already.
It's window.onload - not window.onLoad - Casing is important
Update to
setTimeout(myFunction, 3000);
Place that in your window.onload
JS:
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
}
window.onload = function(){
setTimeout(myFunction, 3000)
}
You can use setInterval instead of setTimeout
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 3) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
setInterval(myFunction, 3000);
JSFiddle

loop a series of image in javascript

i want to loop a series of images in javascript. below is the code i have so far
<html>
<head>
</head>
<body>
<img src="images/image1.jpg" alt="rotating image" width="600" height="500" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'); // change to match image ID
//var imageDir = 'images/'; // change to match images folder
var delayInSeconds = 1; // set number of seconds delay
// list image names
var images = ['1.jpg','2.jpg', '3.jpg', '4.jpg'];
// don't change below this line
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 50);
})();
</script>
</body>
</html>
It can only display the image i have declared in the "var image". if i have 10000 image , how to do that . I have tried using a 'for' loop but it failed .. any suggestions ?? thanks in advance
==============================================================
update version that Joseph recommend :
<html>
<head>
</head>
<body>
<img src="images/1.jpg" alt="rotating image" width="600" height="500" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'), //get the element
var delayInSeconds = 1, //delay in seconds
var num = 0, //start number
var len = 9999; //limit
setInterval(function(){ //interval changer
num = (num === len) ? 0 : num; //reset if limit reached
rotator.src = num + '.jpg'; //change picture
num++; //increment counter
}, delayInSeconds * 1000);
}());
</script>
</body>
</html>
Assuming that images have the same sequential filenames, this would be best when looping through a lot of them:
(function() {
var rotator = document.getElementById('rotator'), //get the element
dir = 'images/', //images folder
delayInSeconds = 1, //delay in seconds
num = 0, //start number
len = N; //limit
setInterval(function(){ //interval changer
rotator.src = dir + num+'.jpg'; //change picture
num = (num === len) ? 0 : ++num; //reset if last image reached
}, delayInSeconds * 50);
}());
AFAIK, you can use the same logic to display the images in small chunk as your browser will crash if you try to display all 10000 images at the same time.So display 5-10 images on the page with your current logic and ask the user to retrieve next set.You can see this kind of implementation in many image sharing applications.Hope this will help you
(function () {
var rotator = document.getElementById('rotator'); // change to match image ID
var imgDir = 'images/'; // change to match images folder
var delayInSeconds = 1; // set number of seconds delay
// Yes I made changes below this line
var num = 0;
var changeImage = function () {
rotator.src = imgDir + num++ + ".jpg";
//var len = rotator.src.length;
if (num == 5) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();

I've hashed together this simple script to rotate pictures and link them to specified URL's, how do I make it pause when I mouseover the picture?

<a id="imageurl" name="imageurl"><img src="Rotating1" id="Rotating1" border="0" alt="Rotating1" name="Rotating1" /></a>
<script language="javascript" type="text/javascript">
function RotateImages(Start)
{
var a = new Array("1.jpg","2.jpg","3.jpg", "4.jpg");
var c = new Array("url1", "url2", "url3", "url4");
var b = document.getElementById('Rotating1');
var d = document.getElementById('imageurl');
if(Start>=a.length)
Start=0;
b.src = a[Start];
d.href = c[Start];
window.setTimeout("RotateImages(" + (Start+1) + ")",3000);
}
RotateImages(0);
</script>
Change your code as Follows:
<a id="imageurl" name="imageurl"><img src="Rotating1" id="Rotating1" border="0" alt="Rotating1" name="Rotating1" onmouseover="StopRotation();" onmouseout="RotateImages();"/></a>
<script language="javascript" type="text/javascript">
var currentImage = -1;
function RotateImages()
{
var a = new Array("1.jpg","2.jpg","3.jpg", "4.jpg");
var c = new Array("url1", "url2", "url3", "url4");
var b = document.getElementById('Rotating1');
var d = document.getElementById('imageurl');
currentImage++;
if(currentImage>= a.length)
currentImage=0;
b.src = a[currentImage];
d.href = c[currentImage];
rotator = window.setTimeout("RotateImages(" + (currentImage+1) + ")",3000);
}
function StopRotation()
{
window.clearTimeout(rotator);
}
RotateImages();
</script>
added Function "StopRotation"
added onmouseover and onmouseout-Events to the Image Tag
Rotation continues at the current Image.
The return value of setTimeout can be passed to cancelTimeout to stop the rotation. You might save it to a variable, then cancel the timeout on MouseIn and restart it on MouseOut.

Categories