...

View Full Version : JavaScript conditional operator



tl87
08-30-2008, 10:55 AM
I am trying to make a function to toggle an image src when a button (another image) is clicked... This is what I have so far, and it doesn't work. It does work when you adapt it to change other properties of the image, such as width, but not the src... any ideas of what could be wrong?
Thanks

<script>
function click(obj)
{
var el = document.getElementById(obj);
el.src= (el.src== "a.png" ? "b.png" : "a.png") ;
}
</script>

<img id="im" src="a.png">

<img src="button.png" onclick="click('im')" >

Philip M
08-30-2008, 11:27 AM
click is a reserved word. Rename the function.

tl87
08-30-2008, 11:41 AM
click is a reserved word. Rename the function.

It is the same when I rename it.

The function works for one click if the image starts as b.png (it changes to a.png) but doesnt change back when the script is run again. It also does nothing if you start with a.png...

coothead
08-30-2008, 12:12 PM
Hi there tl87,

and a warm welcome to these forums. ;)

try it like this...


<script type="text/javascript">
var flag=1;;
function chick(obj){
var el=document.getElementById(obj);
flag=(flag==0)?(el.src='a.png',flag=1):(el.src='b.png',flag=0);

}
window.onload=function(){
document.getElementById('om').onclick=function() {
chick('im');
}
}
</script>

<img id="im" src="a.png" alt="">

<img id="om" src="button.png" alt="" >

coothead

tl87
08-30-2008, 01:21 PM
thanks got it to work!

tl87
08-30-2008, 01:25 PM
How do I make the "flag" specific to the (obj) so I can run the same script in multiple places on one page?

Arty Effem
08-30-2008, 01:39 PM
<script>
function click(obj)
{
var el = document.getElementById(obj);
el.src= (el.src== "a.png" ? "b.png" : "a.png") ;
}
</script>
The actual cause of the error is that src contains the entire path not just the filename, Try this:

function Click(obj)
{
var el = document.getElementById(obj);
el.src= (el.src.match("a.png") ? "b.png" : "a.png") ;
}

tl87
08-30-2008, 01:49 PM
Thanks that solves both problems in one!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum