0

So, I have the following jQuery code that slides a list up to replace another list when a button is clicked. The button's text is then changed to "dev languages" so that the user knows to click the button again to go back to the original list. When the user clicks the button again to go back to that original list how do I get the button to change back to it's original text?

$(document).ready(function() {

    $(".projects").on("click", function(){

        $(".devList").slideToggle();
        $(".devButton").slideToggle();
        $(".projects").text("Development Languages");
    });
});
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
Exziled
  • 473
  • 5
  • 20
  • 2
    Um...using the `.text()` method again? Or are you asking how to know whether the current click is changing to the new value or the old value (given you slide the other items using a toggling method)? – nnnnnn Mar 09 '15 at 02:49
  • Check the current value and change accordingly. No magic here. – j08691 Mar 09 '15 at 02:51
  • Keep it simple, replace `$(".projects").text("Development Languages");` with `$(".projects").text()=="Development Languages" ? $(".projects").text("Something Else") : $(".projects").text("Development Languages");` – NewToJS Mar 09 '15 at 03:00

2 Answers2

1

There are many ways to do this, the simplest of which is to use the .text() method to retrieve the current text of the button and test it:

var currentText = $(this).text();
if (currentText === "Development Languages")
    $(this).text("Whatever the old label was");
else
    $(this).text("Development Languages");

However, you may not want to have to hard-code the different labels within your JavaScript. So you could put it in the markup like this:

<button class="projects" data-alternate-label="Development Languages">Click me</button>

...and then have more generic JavaScript that checks the data- attribute to see what the alternate label is when clicked, storing the previous text for use after the next click:

    var $this = $(this),
        alternateLabel = $this.data("alternate-label");
    $this.data("alternate-label", $this.text());
    $this.text(alternateLabel);

That way you could have multiple buttons with associated lists on the same page and still only need the one click handler to manage them, as shown here: http://jsfiddle.net/c5584bgr/2/

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • This is perfect thank you so much! I'm just learning jQuery a bit and was not sure of how to use conditionals! This makes perfect sense now that I look at it and apply it to my code! Thanks a bunch! – Exziled Mar 09 '15 at 03:04
0

You can check what the current text is and change it depending on the state:

if ($(".projects").text() === "Development Languages") {
  $(".projects").text("New Text");
} else {
  $(".projects").text("Development Languages");
}
Ivan
  • 10,052
  • 12
  • 47
  • 78