robert_gsfame Posted July 25, 2010 Share Posted July 25, 2010 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 Quote Link to comment Share on other sites More sharing options...
haku Posted July 25, 2010 Share Posted July 25, 2010 What does the HTML look like? Also, can you please wrap your code in code tags? It's the # button above the text area you type in. Edit: This should be: if(document.getElementById("img2"+x).src == "image/buttonopen2.gif") The way you wrote it, it would always evaluate to true. Quote Link to comment Share on other sites More sharing options...
haku Posted July 25, 2010 Share Posted July 25, 2010 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.