Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Text toggles only once

Tags:

html

jquery

I have a simple script that should change from + to - when the Content is open, and backwards.
But now, when it changes to -, it stays as - no matter what. Even if you collapse the content, it still stays as -.

I've tried to reverse the functions, but it just did the same with the +.

jQuery

$(document).ready(function(){
    $("#expanderHead").click(function(){
        $("#expanderContent").slideToggle();
    if ($("#expanderSign").text() != "+"){
        $("#expanderSign").html("-")
    } else {
        $("#expanderSign").html("+")
    }
    });
});

HTML

<span id="expanderHead" style="cursor:pointer;">
    Lorem ipsum Lorem ipsum Lorem ipsum.
    <span id="expanderSign">+
    </span></span>
    <div id="expanderContent" style="display:none; color: green;">
    <sup><p>Lorem ipsumLorem ipsumLorem ipsum<br>
    Lorem ipsumLorem ipsumLorem ipsumLorem ipsum,<br>
     Lorem ipsumLorem ipsumLorem ipsum.</p>
     </sup>
  </div>
like image 998
Claudio Avatar asked Dec 16 '13 08:12

Claudio


2 Answers

Your logic is wrong, you're saying if the sign is not currently + (it is -), then set it to -. The sign will always be -.

Change your condition to:

if ($("#expanderSign").text() == "+"){

Or how about using a function with your text() method:

$("#expanderSign").text(function(i,v){
    return v == '-' ? '+' : '-';
})

JSFiddle

like image 168
George Avatar answered Oct 03 '22 07:10

George


Your condition check logic is the wrong way around, try this:

if ($("#expanderSign").text() == "+"){
    $("#expanderSign").html("-")
}
else {
    $("#expanderSign").html("+")
}
like image 36
Rory McCrossan Avatar answered Oct 03 '22 07:10

Rory McCrossan