Jump to content

image src problem


robert_gsfame

Recommended Posts

I have this code to change the image of the toggle

 

<script type="text/javascript">

function open(x)

{

if(document.getElementById("img2"+x).src="image/buttonopen2.gif")

  {

    document.getElementById("img2"+x).setAttribute("src", "image/buttonclose2.gif");

  }else{

          document.getElementById("img2"+x).setAttribute("src", "image/buttonopen2.gif");

  }

}

</script>

 

when page loaded, the image src has been set to "image/buttonopen2.gif"

the problem is that when i click on the image, the img src turn into buttonclose2.gif...but afterward when i try to click again on the image, i wish to have the image turn back into buttonopen2.gif but in fact nothing happened

 

thx

 

Link to comment
https://forums.phpfreaks.com/topic/208819-image-src-problem/
Share on other sites

And finally, you can clean up your code like this:

 

<script type="text/javascript">
function open(x)
{
  var target = document.getElementById("img2"+x);
  if(target.getAttribute("src") == "image/buttonopen2.gif")
  {
    target.setAttribute("src", "image/buttonclose2.gif");
  }else{
    target.setAttribute("src", "image/buttonopen2.gif");
   }
}
</script>

By putting the DOM element into a var, you save your script from having to traverse the DOM to look for the element each time. The way you had it, it was traversing the DOM once to find the element and check it's src, then it had to traverse it again to find the element to change the src. This is quite inefficient, and with multiple scripts on your page, or on a slow browser, will really slow things down.

Link to comment
https://forums.phpfreaks.com/topic/208819-image-src-problem/#findComment-1090857
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.