tags:

views:

1765

answers:

5

I have the next html code

<h3 id="headerid"><span onclick="expandCollapse('headerid')">&uArr;</span>Header title</h3>

I would like to toggle between up arrow and down arrow each time the user clicks the span tag.

function expandCollapse(id) {   
    var arrow = $("#"+id+" span").html(); // I have tried with .text() too
    if(arrow == "&dArr;") {  
    $("#"+id+" span").html("&uArr;");    
    } else {     
    $("#"+id+" span").html("&dArr;");    
    }
}

My function is going always the else path. If i make a javacript:alert of arrow variable i am getting the html entity represented as an arrow. How can i tell jquery to interpret arrow variable as a string and not as html.

Thanks in advanced.

+1  A: 

Check out the .toggle() effect.

Here is something similar i was playing with earlier.

HTML:

<div id="inplace">
<div id="myStatic">Hello World!</div>
<div id="myEdit" style="display: none">
<input id="myNewTxt" type="text" />
<input id="myOk" type="button" value="OK" />
<input id="myX" type="button" value="X" />
</div></div>

SCRIPT:

 $("#myStatic").bind("click", function(){
    $("#myNewTxt").val($("#myStatic").text());
    $("#myStatic,#myEdit").toggle();
 });
 $("#myOk").click(function(){
    $("#myStatic").text($("#myNewTxt").val());
    $("#myStatic,#myEdit").toggle();
 });
 $("#myX").click(function(){
    $("#myStatic,#myEdit").toggle();
 });
jms
A: 

Maybe you're not getting an exact match because the browser is lower-casing the entity or something. Try using a carat (^) and lower-case "v" just for testing.

Edited - My first theory was plain wrong.

Neall
+3  A: 

When the HTML is parsed, what JQuery sees in the DOM is a UPWARDS DOUBLE ARROW ("⇑"), not the entity reference. Thus, in your Javascript code you should test for "⇑" or "\u21d1". Also, you need to change what you're switching to:

function expandCollapse(id) {
    var arrow = $("#"+id+" span").html();
    if(arrow == "\u21d1") {     
        $("#"+id+" span").html("\u21d3");                           
    } else {            
        $("#"+id+" span").html("\u21d1");                           
    }
}
jelovirt
+1  A: 

If you do an alert of arrow what does it return? Does it return the exact string that you're matching against? If you are getting the actual characters '⇓' and '⇑' you may have to match it against "\u21D1" and "\u21D3".

Also, you may want to try &#8657; and &#8659; since not all browsers support those entities.

travis
+1  A: 

Use a class to signal the current state of the span. The html could look like this

<h3 id="headerId"><span class="upArrow">&uArr;</span>Header title</h3>

Then in the javascript you do

$( '.upArrow, .downArrow' ).click( function( span ) {
    if ( span.hasClass( 'upArrow' ) )
        span.text( "&dArr;" );
    else
        span.text( "&uArr;" );
    span.toggleClass( 'upArrow' );
    span.toggleClass( 'downArrow' );
} );

This may not be the best way, but it should work. Didnt test it tough

Juan