SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
-
Jun 14, 2007, 00:01 #1
- Join Date
- Oct 2006
- Location
- Queensland, Australia
- Posts
- 852
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
What's wrong with this simple function?
Why isn't this doing what I want?
Code JavaScript:function switchImage(obj) { if (obj.src == 'images/minus.gif') { obj.src = 'images/plus.gif'; } else { obj.src = 'images/minus.gif'; } }
basically, this function is meant to check what image is currently set as the source, and swap it with the other image. I'm using it as part of a collapsing tree. What's happening at the moment is it will change the sign from plus.gif to minus.gif (as the if statement returns false so it performs the else command) but the if statement doesn't parse as true even when 'obj' is set to 'images/minus.gif'. I'm a javascript noob, so I could have made a really basic mistake.
I always call the function within an img tag like so onclick="switchImage(this)". Here's the exact img tag I'm using incase that helps.
Code HTML4Strict:<img src="images/plus.gif" onclick="switchImage(this);">
Heaps of brownie points to those who help
Cheers!
-
Jun 14, 2007, 00:11 #2
- Join Date
- May 2003
- Location
- Cambridge, UK
- Posts
- 2,366
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Use alert() to check what the src is set to - it may be that once you've changed it, the obj.src is not exactly equal to that string.
-
Jun 14, 2007, 00:12 #3
- Join Date
- Jan 2007
- Location
- Belgium
- Posts
- 591
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
The obj.src will contain the entire URL to the image, so images/plus.gif would become http://www.mydomain.com/images/plus.gif.
FOR SALE: 1 set of morals, never used, will sell cheap
-
Jun 14, 2007, 00:30 #4
- Join Date
- Sep 2006
- Posts
- 731
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
img.src will contain the full path and therefore won't match what you've specified. You need to check for a substring:
Code:function switchImage(obj) { obj.src == obj.src.match("images/minus.gif")?'images/plus.gif':'images/minus.gif'; }
Last edited by Logic Ali; Jun 14, 2007 at 02:59.
Tab-indentation is a crime against humanity.
-
Jun 14, 2007, 02:33 #5
- Join Date
- Jun 2007
- Posts
- 28
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
If possible just check for the filename instead of the path in your conditional statement. That way you don't have to know exactly what the path looks like. You could do this by using regular expressions:
Code JavaScript:function switchImage(obj) { re = new RegExp("minus.gif", "i"); if (re.test(obj.src)) obj.src = "images/plus.gif"; else obj.src = "images/minus.gif"; }
Bookmarks