Switch image when page refreshes using Javascript - javascript

How to switch an image when the page refreshes, using Javascript?
Let's say I have 2 images:
ImageA.jpg
ImageB.jpg
I want to switch those images at locationA and locationB when the page is refreshed.
Simulation:
- Page Refresh #1
<img id='locationA' src='ImageA.jpg'>
<img id='locationB ' src='ImageB.jpg'>
- Page Refresh #2
<img id='locationA' src='ImageB.jpg'>
<img id='locationB ' src='ImageA.jpg'>
- Page Refresh #3
<img id='locationA' src='ImageA.jpg'>
<img id='locationB ' src='ImageB.jpg'>
[Update #1]
I try this implementation, but it doesn't work. Could anyone tell me whats wrong with this code?
<html>
<head>
<script type="text/javascript">
var images = [];
images[0] = "I_am_Super_Magnet%21.jpg";
images[1] = "World_In_My_Hand%21.jpg";
var index = sessionStorage.getItem('index');
if(index) index = 0;
if(index==0)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index+1];
index = index + 1;
}
else if(index==1)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index-1];
index = index - 1;
}
sessionStorage.setItem('index', index);
</script>
</head>
<body>
<img id='locationA' src=''>
<img id='locationB' src=''>
</body>
</html>
[Update #2]
Tested on:
FF 16.0.1 --> Working!
IE 8 --> doesn't work
Here is the code:
<html>
<head>
<script type="text/javascript">
function switchImage()
{
var images = [];
images[0] = "I_am_Super_Magnet%21.jpg";
images[1] = "World_In_My_Hand%21.jpg";
var index = sessionStorage.getItem('index');
if(index == null) index = 0;//set index to zero if null
index = parseInt(index);// parse index to integer, because sessionStorage.getItem() return string data type.
if(index == 0)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index+1];
index = index + 1;
}
else if(index == 1)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index-1];
index = index - 1;
}
sessionStorage.setItem('index', index);
}
</script>
</head>
<body onload="switchImage()">
<img id='locationA' src='src_locationA'>
<img id='locationB' src='src_locationB'>
</body>
</html>
Thanks to Jack for the
clue! and thanks to Jon Kartago
Lamida for
the sample!
Thanks.

Set a flag variable in your cookie ( Check Javascript Cookie SO Question for setting a cookie ).
Every time the page loads, ( in your onload function ) check the value of the flag.
Say if value is 0 . Show ImageA in LocationA. Then invert the flag value to 1.
Else if value is 1 . Show ImageB in LocationA. Then invert the flag value to 0.
The flag value will be stored in your cookie.
Hope this helps,
Shoubhik

I try to give example according to Jack, using localStorage. Most modern browser have support this. I haven't this this code yet, but more or less should be like this.
<html>
<head>
<script type="text/javascript">
function init(){
var imageA = 'imageA.jpg';
var imageB = 'imageB.jpg';
// state maintaned using localStorage
var toggle = localStorage.getItem('toggle');
if(toggle) toggle = "A"; // if no state yet, initialize
if(toggle == "A"){
toggle = "B";
document.getElementById('locationA').src=imageA;
document.getElementById('locationB').src=imageB;
}else{
toggle = "A";
document.getElementById('locationA').src=imageB;
document.getElementById('locationB').src=imageA;
}
// put state back to local storage
localStorage.setItem('toggle', toggle);
}
</script>
</head>
<body onload="init()">
<img id='locationA' src=''>
<img id='locationB' src=''>
</body>
</html>

Base on Damien_The_Unbeliever comment I create this answer post for my own question.
This is final working solution that I use.
[Update #3]
Tested on:
FF 16.0.1 --> Working!
IE 8 --> Working!
Chrome 24 --> Working! (Note: this browser need a little extra effort to make it can read cookie. see this link)
Basically the code is still same as Update #2, the different is I use cookie instead of sessionStorage. Here is the complete code:
<html>
<head>
<script type="text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function switchImage()
{
var images = [];
images[0] = "I_am_Super_Magnet%21.jpg";
images[1] = "World_In_My_Hand%21.jpg";
var index = readCookie('index'); //sessionStorage.getItem('index');
if(index == null) index = 0;//set index to zero if null
index = parseInt(index);// parse index to integer, because sessionStorage.getItem() return string data type.
if(index == 0)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index+1];
index = index + 1;
}
else if(index == 1)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index-1];
index = index - 1;
}
createCookie('index', index); //sessionStorage.setItem('index', index);
}
</script>
</head>
<body onload="switchImage()">
<img id='locationA' src='src_locationA'>
<img id='locationB' src='src_locationB'>
</body>
</html>

Related

Image Changing Button using JavaScript

I had a look here and here for my answer but found that the code was far too long for such a simple process.
Below, my code shows a basic Image Changer by having the 'image' changed to the different .jpg's in an array, located in the same file.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class = "change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
document.getElementById("image").src = imageSources[i]
}
}
</script>
</body>
</html>
In theory, because I've embedded the script within the HTML it should work like a dream, but the image seems to get stuck on the yellow light. Is there a repeat button click phase I'm missing?
Thanks.
There is no need to use a loop. You can get reference to the button using document.getElementsByClassName("change-image")[0];. Then you can add an event lister to trigger on each button click.
Each time a user clicks you iterate through the array by one.
You could look at doing something like this:
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click',function() {
if(index === imageSources.length ) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
Here is the complete code, which works. If you inspect the img element you will see that it updates.
<!DOCTYPE html>
<html>
<body>
<img id="image" src="blank_light.jpg" style="width:100px">
<p></p>
<button class="change-image">Change Lights</button>
<script>
var imageSources = ["green_light.jpg", "yellow_light.jpg", "red_and_yellow_light.jpg", "red_light.jpg", "blank_light.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click', function() {
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
});
</script>
</body>
</html>
Funny implementation -))
document.getElementById("changer").addEventListener("click", function(){
var i = document.getElementById("source");
var images = [
"http://lorempixel.com/400/200/sports",
"http://lorempixel.com/400/200/animals",
"http://lorempixel.com/400/200/nature"
];
var ord = parseInt(i.dataset.order);
nextImage = function(prev) {
return (prev+1 >= images.length ? (prev + 1)%images.length : prev+1);
}
document.getElementById("source").src = images[nextImage(ord)];
i.dataset.order = ord + 1;
})
<img id="source" data-order="0" src="http://lorempixel.com/400/200/sports">
<button id="changer">change</button>

Loop through images in HTML with a timer

This is my code, it only outputs the original red image and i don't understand how i'm supposed to make the code able to loop. Could someone help as I need this code desperately?
<!DOCTYPE html>
<html>
<head>
<h1> The traffic script</h1>
<script>
var list = [
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/amber.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/green.jpg"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('red');
image.src=list[index];
}
window.onload = changelights;
</script>
</head>
<body>
<img id="red" src="H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg">
</body>
</html>
Use SetInterval - this is not a loop like a for loop, etc. It is simply a block of code that will get triggered every x miliseconds.
var list = [
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/red.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/amber.jpg",
"H:/GCSE COMPUTING/a452/traffic thingy/traffic/bleh/green.jpg"
];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length) index = 0;
var image = document.getElementById('red');
image.src=list[index];
}
setInterval(function(){changeLights()}, 4000);
This will call changeLights every 4 seconds. Also - be careful asking GCSE questions here especially the course work.
JavaScript has a built-in interval method, which can be used as a loop in this case.
var backgroundInterval = setInterval(function() {
changeLights();
if(index == (list.length - 1)) {
clearInterval(backgroundInterval); // stop the loop when it hits last image
}
}, 4000); // every 4000 ms, or 4s

autorefreshing an image in HTML with 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>

How do I access and modify an image in an HTML page using javascript?

My HTML page has an image with id img. The idea is that by clicking first, previous, or next, the user can navigate through a set of images. How do I do this using JavaScript?
This should be a good start for you:
<script>
var imgs = ["img1.png","img2.png","img3.png"]; // copy images to the same dir
var index = 0;
</script>
<img src="img1.png" onclick="this.src=imgs[++index%imgs.length]"/>
click the image to slide.
If you need buttons, see this example:
<img id="clicker" src="img1.png"/>
Prev
Next
First
Last
<script>
var imgs = ["img1.png","img2.png","img3.png"];
var index = 0;
var clicker = document.getElementById("clicker");
function prev() { clicker.src = imgs[--index%imgs.length]; }
function next() { clicker.src = imgs[++index%imgs.length]; }
function first() { clicker.src = imgs[index=0]; }
function last() { clicker.src = imgs[index=imgs.length-1]; }
</script>
The return false means that default action on click (follow the link) is supressed. Javascript can access elements i.e. using id (see clicker here). Once you get comfortable with this and you start to solve browser compatibility problems, it is good idea to continue with jQuery (as the other suggests), MooTools or other framework.
Use jQuery!
var myImg = $("#myimg");
$("#next").click(function(){
var id = myImg.attr("data-id") + 1;
myImg.attr("src", "image"+id+".jpg");
});
$("#prev").click(function(){
var id = myImg.attr("data-id") -1;
myImg.attr("src", "image"+id+".jpg");
});
HTML:
<img id="myimg" src="image1.jpg" data-id="1">
Next<br>
Previous<br>
This is a very dummy example. There are numerous slideshow plugins out there!
No need jQuery:
<script type='text/javascript'>
window.onload = function() {
var imageSrcs= ['1.jpeg', '2.jpg', '3.jpg'];
var index = 0;
var image = document.getElementById('img');
var previous = document.getElementById('previous');
previous.onclick = function() {
index -= 1;
if(index < 0) index = imageSrcs.length - 1;
image.src = imageSrcs[index];
}
var next = document.getElementById('next');
next.onclick = function() {
index += 1;
if(index == imageSrcs.length) index = 0;
image.src = imageSrcs[index];
}
}
</script>
And html:
<img src='1.jpeg' id='img'>
<div>
<span id='previous'>Previous</span>
<span id='next'>Next</span>
</div>
You do not need a library for this. Something like this will change the image url, where "theImg" is the id of the image:
document.getElementById("theImg").src = "newUrl.png";
To do it without explicit ids, this will change the url where i is the index of the image:
document.getElementsByTagName("img")[i].src = "newUrl.png";
Try something like this (untested):
LOAD JQUERY:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
JAVASCRIPT:
<script type='text/javascript'>
var lst_src = ['img1.jpg', 'img2.png', 'img3.gif'];
$('a', '#nav').click(function(e) {
e.preventDefault();
var src_current = $('#img').attr('src');
var index = lst_src.indexOf(src_current);
var len = lst_src.length;
var action = $(this).attr('class');
switch ($action) {
case 'previous' : var i = index - 1;
if (i < 0) src_current = lst_src[len + i];
else src_current = lst_src[i];
break;
case 'next' : var i = index + 1;
if (i > len) src_current = lst_src[i - len];
else src_current = lst_src[i];
break;
case 'first' : src_current = lst_src[0];
break;
case 'last' : src_current = lst_src[len - 1];
break;
}
$('#img').attr('src', src_current);
});
</script>
HTML: Use the class of a link to denote the required action:
<img id='img' src='img1.jpg'>
<p id='nav'>
<a href='' class='first'>←←First</a>
<a href='' class='previous'>←Previous</a>
<a href='' class='next'>Next→</a>
<a href='' class='last'>Last→$rarr;</a>
</p>

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);
})();

Categories