Forum Moderators: open
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
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
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..