Forum Moderators: open

Message Too Old, No Replies

Setting variable equal to getElementById Statement

         

Jeremy_H

7:07 pm on Jun 28, 2006 (gmt 0)

10+ Year Member



Hello,

I have some lines of code that read like this:

<input ... onClick="document.getElementById('d1').src='/img/d1.jpg';">
<input ... onClick="document.getElementById('d1').src='/img/d2.jpg';">
<input ... onClick="document.getElementById('d1').src='/img/d3.jpg';">
<input ... onClick="document.getElementById('d1').src='/img/d4.jpg';">
<input ... onClick="document.getElementById('d1').src='/img/d5.jpg';">

I would like to reduce my code by doing something like this, but it doesnt seem to work:

<script type="text/javascript">var s=document.getElementById('d1').src;</script>
<input ... onClick="s='/img/d1.jpg';">
<input ... onClick="s='/img/d2.jpg';">
<input ... onClick="s='/img/d3.jpg';">
<input ... onClick="s='/img/d4.jpg';">
<input ... onClick="s='/img/d5.jpg';">

Any advice?

Thanks

jshanman

7:47 pm on Jun 28, 2006 (gmt 0)

10+ Year Member



You are currently storing a string (the value of src) into the "s" variable and changing the string value of "s" in the onclick events.

What you want is this:

<script type="text/javascript">var s=document.getElementById('d1');</script>
<input ... onClick="s.src='/img/d1.jpg';">
...

This stores the document Element Object returned by getElementById into the s variable so you can change the objects properties.

- JS

Bernard Marx

9:25 pm on Jun 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The element, "d1", will need to appear in the HTML before the assignment statement, or there'll be an error.

Alternatively, you could wrap up document.getElementById in a function with a less verbose name (I usually do). However, since you appear to be doing something very similar quite a lot, you could wrap the whole process into a function..

function d1(n)
{
document.getElementById("d1").src = "/img/d"+n+".jpg";
}

Then..

onclick=d1(2)

etc..

Jeremy_H

8:36 pm on Jun 29, 2006 (gmt 0)

10+ Year Member



Thanks so much, with your feedback I was able to make a working script that was faster and better.

Thanks.