Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle image src attribute using Javascript

I am trying to change the HTML image src using Javascript. I have two images Plus.gif and Minus.gif.I have inserted HTML img tag and have written a Javascript function to change the image src when clicked.

Problem is that I want to change it back again when user clicks on the image. For example when the page is loaded the Plus.gif shows and when user clicks on it the image it changes to Minus.gif.

I want it so, when the image is Minus.gif and user clicks on it this should be changed to Plus.gif.

Here is my Javascript function:

<script language="javascript" type="text/javascript">
  function chngimg() {
    var img = document.getElementById('imgplus').src; //= 'Images/Minus.gif';

    if (img) {
      document.getElementById('imgplus').src = 'Images/Minus.gif';
    } else if (!img) {
      document.getElementById('imgplus').src = 'Images/Plus.gif';
      alert(img);
    }

  }
</script>

Image tag:

<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()"   />
like image 377
user1583775 Avatar asked Dec 08 '25 18:12

user1583775


2 Answers

See the changes I made to make it working

<script language="javascript" type="text/javascript">
    function chngimg() {
        var img = document.getElementById('imgplus').src;
        if (img.indexOf('Plus.gif')!=-1) {
            document.getElementById('imgplus').src  = 'Images/Minus.gif';
        }
         else {
           document.getElementById('imgplus').src = 'Images/Plus.gif';
       }

    }
</script>

<img id="imgplus" alt="" src="Images/Plus.gif" onmouseover="this.style.cursor='pointer'" onclick="chngimg()"   />

Hope that resolves your question.

like image 93
Piyush-Ask Any Difference Avatar answered Dec 10 '25 15:12

Piyush-Ask Any Difference


One way would be to add a toggle variable in your function:

var toggle = false;
function chngimg() {
    if (toggle === true) {
        document.getElementById('imgplus').src  = 'Images/Minus.gif';
    } else {
       document.getElementById('imgplus').src = 'Images/Plus.gif';
       alert(img); 
    }
    toggle = !toggle; 
}

Note that it's a better practice to use a sprite for this kind of thing. If you're using two images, the user experience is going to be clunky, because the first time they click the image, there will be a slight delay while the second image loads.

Ideally you would have the two images as a sprite sheet, and be using JQuery. Then you could just do it like this.

HTML

<img id="imgplus" src="Images/Sprite.gif" onclick="chngimg()" />

CSS

#imgplus .clicked { background-position: 0 -30px; }

Javascript

function chngimg() {
    $("#imgplus").toggleClass("clicked");
}
like image 28
McGarnagle Avatar answered Dec 10 '25 16:12

McGarnagle