Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Toggling background image with JavaScript 1

Status
Not open for further replies.

NuJoizey

MIS
Aug 16, 2006
450
US
why the heck doesn't this code work?

Code:
            if(window.document.getElementById(elm2).style.backgroundImage=='url(images/expand_arrow.png)' || window.document.getElementById(elm2).style.backgroundImage=='')
            {
                window.document.getElementById(elm2).style.backgroundImage='url(images/collapse_arrow.png)';
              
            }
            else
            {
                window.document.getElementById(elm2).style.backgroundImage='url(images/expand_arrow.png)';
            }

Uncommitted, except to looking good. Constantly judging.
Always on the verge of being upset.
 
Hi

The browsers internally transform the value so the equality test will not work. For example if you set it to 'url(images/expand_arrow.png)', when reading it back you will get
[ul]
[li]Gecko : 'url([highlight]"[/highlight]images/expand_arrow.png[highlight]"[/highlight])'[/li]
[li]WebKit : 'url([highlight][/highlight]images/expand_arrow.png)',[/li]
[li]Presto : 'url([highlight]"[/highlight]images/expand_arrow.png[highlight]"[/highlight])'[/li]
[/ul]
So better search only for a substring :
Code:
[b]var[/b] elmobj[teal]=[/teal]document[teal].[/teal][COLOR=darkgoldenrod]getElementById[/color][teal]([/teal]elm2[teal])[/teal]
[b]if[/b] [teal]([/teal]elmobj[teal].[/teal]style[teal].[/teal]backgroundImage[highlight][teal].[/teal][COLOR=darkgoldenrod]indexOf[/color][teal]([/teal][green][i]'expand'[/i][/green][teal])!=-[/teal][purple]1[/purple][/highlight]
[teal]||[/teal] elmobj[teal].[/teal]style[teal].[/teal]backgroundImage[teal]==[/teal][green][i]''[/i][/green][teal])[/teal] [teal]{[/teal]
  elmobj[teal].[/teal]style[teal].[/teal]backgroundImage[teal]=[/teal][green][i]'url(images/collapse_arrow.png)'[/i][/green][teal];[/teal]
[teal]}[/teal] [b]else[/b] [teal]{[/teal]
  elmobj[teal].[/teal]style[teal].[/teal]backgroundImage[teal]=[/teal][green][i]'url(images/expand_arrow.png)'[/i][/green][teal];[/teal]
[teal]}[/teal]


Feherke.
 
that is so incredibly helpful. thank you so much.

Obviously, I don't write a ton of javascript, but whenever I do it seems that I am forever running into these kinds of perplexing issues.



Uncommitted, except to looking good. Constantly judging.
Always on the verge of being upset.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top