Bram Vanroy
Bram Vanroy

Reputation: 28505

Text doesn't get toggled back

I have this small toggle script, which toggles a panel, a class and text. I'm having trouble toggling the text though. It changes on the first click, but doesn't change back afterwards.

Here is a fiddle. And here is the relevant code:

var visibleText = "Hide";
var hiddenText = "Show";
var textChange = $("#hidewrap a span");
var dynText = textChange.text() == visibleText ? hiddenText : visibleText;

textChange.text(dynText);

Thanks!

Upvotes: 1

Views: 66

Answers (2)

Tats_innit
Tats_innit

Reputation: 34107

working demo fiddle link here

Visible text needs to become hidden and hidden should be updated with current visible text,

Shifting these 3 lines in bind event of click will do the trick for you:

   var visibleText = $("#hidewrap a span").text();

    var dynText = textChange.text() == visibleText ? hiddenText : visibleText;
    hiddenText = textChange.text();

Jquery code

$(document).ready(function() {
    var panel = $("#topnav nav");
    var button = $("#hidewrap");
    var hiddenClass = "hidden";
    var visibleText = $("#hidewrap a span").text(); //"Hide";
    var hiddenText = "Show";
    var textChange = $("#hidewrap a span");


    var classAdd = $("aside#topnav");

    button.click(function(e) {
        var visibleText = $("#hidewrap a span").text();

        var dynText = textChange.text() == visibleText ? hiddenText : visibleText;
        hiddenText = textChange.text();
        e.preventDefault();
        e.stopImmediatePropagation();

        textChange.text(dynText);
        classAdd.toggleClass(hiddenClass);
        panel.slideToggle("fast");
    });
});​

Upvotes: 1

Dean
Dean

Reputation: 288

Firstly, here's the answer.

Secondly, the explanation: Your logic to check the text of the <span></span> element was in $.ready method. jQuery invokes this method internally once per page load, therefor the logic would only check the text value of the span once. I simply moved the logic check var dynText = textChange.text() == visibleText ? hiddenText : visibleText; into the .click so that the check is carried out every time the link is clicked, as opposed to once per page load.

Upvotes: 2

Related Questions