0

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.

Community
  • 1
  • 1
CodeGhoib
  • 23
  • 1
  • 5
  • You'd have to maintain state within JavaScript, either with cookie or local storage and toggle it at every page load; server side state management is also possible of course. Lastly, you could randomize the positions (though that would not always result in the same behaviour). – Ja͢ck Jan 15 '13 at 06:56
  • did you mean like [this one](http://stackoverflow.com/questions/1270468/does-anyone-know-how-can-i-keep-the-javascript-variable-even-though-the-page-has) – CodeGhoib Jan 15 '13 at 07:01
  • 1
    That would sound like a good start; [`sessionStorage`](https://developer.mozilla.org/en-US/docs/DOM/Storage#sessionStorage) is another option to think about (more modern browsers support it). – Ja͢ck Jan 15 '13 at 07:07
  • Thanks for the response and suggestion. I will try it! – CodeGhoib Jan 15 '13 at 07:12
  • Hi Jack, I try to implemented the code based on [Jon Kartago Lamida](http://stackoverflow.com/users/946199/jon-kartago-lamida) sample, but it doesn't work :( – CodeGhoib Jan 15 '13 at 07:40
  • If you have a solution that works for you, post it as an *answer*, not an edit to your question. And, don't update the title. The way it works on SO is we know a question is answered when you *accept* an answer(by ticking next to it). You're allowed to do this (after a delay, I think) even with your own answers. – Damien_The_Unbeliever Jan 15 '13 at 08:14

3 Answers3

0

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.

  1. Say if value is 0 . Show ImageA in LocationA. Then invert the flag value to 1.
  2. 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

Community
  • 1
  • 1
sbose
  • 1,791
  • 5
  • 24
  • 46
0

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>
Jon Kartago Lamida
  • 827
  • 1
  • 7
  • 12
0

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>
Community
  • 1
  • 1
CodeGhoib
  • 23
  • 1
  • 5