Web Analytics Made Easy -
StatCounter Toggling/Switching between multiple images with onClick - CodingForum

Announcement

Collapse
No announcement yet.

Toggling/Switching between multiple images with onClick

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Toggling/Switching between multiple images with onClick

    Hi,

    I have created a long list of items. For each item, there is 1 image. In my case, I use the same image each time.

    I would like to use JS to allow users to check an item by clicking on it. Please note, I am not using radio buttons or any other forms.

    This is my JS function:

    Code:
    function changeimage(img, new_src) {
       var cur_src = img.src.substring(img.src.lastIndexOf("/")+1);
       if (cur_src == new_src) {
          img.src = img.old_src;
       } 
       else {
          img.old_src = cur_src;
          img.src = new_src;
       }
    }
    It is triggered using this:

    Code:
    <img onclick="changeimage(this, '2.png')" src="1.png" />
    It works for each image. It switches to 2.png when a user clicks on each instance of that image. But how do you make sure it switches back to 1.png on the next click, and so on, effectively creating a switch for multiple instances of the same image?

    Thanks!

  • #2
    Never find, I already found the solution.

    Code:
       var cur_src = img.src.substring(img.src.lastIndexOf("/")+1);
       if (cur_src == "1.png") {
          img.src = "2.png";
       } 
       if (cur_src == "2.png") {
          img.src = "2.png";
       }
    So simple, but was code-blind for a second.

    Comment


    • #3
      Well, yeah...but why make two IF tests???

      If there are ONLY two possible values:
      Code:
         img.src =  ( img.src.indexOf("1.png") >= 0 ) "2.png" : "1.png";
      Also, you are looking for the substring that starts after the last / characters, but then the src you replace has no / character at all. So why search for the / ???

      But anyway, just using indexOf (or, I guess, match) is adequate.
      Be yourself. No one else is as qualified.

      Comment

      Working...
      X