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.
 
     
     
    