Toggle image src attribute using Javascript

妖精的绣舞 提交于 2019-11-29 08:34:57

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.

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

I have successfully used this general solution in pure JS for the problem of toggling an img url:

function toggleImg() {
  let initialImg = document.getElementById("img-toggle").src;
  let srcTest = initialImg.includes('initial/img/url');
  let newImg = {
    'true':'second/img/url', 
    'false':'initial/img/url'}[srcTest];

  return newImg;
}

Then call toggleImg() inside whatever event handler you use....

someButton.addEventListener("click", function() {
  document.getElementById("img-toggle").src = toggleImg();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!