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
Share on other sites

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.

Link to comment
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.