Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Text with jQuery

Tags:

jquery

I've found a a few articles here on this topic but none seem to answer exactly what I'm looking for.

Here is my current code:

    $(".email-slide").click(function(){
    $("#panel").slideToggle("slow");
    $(this)
    .text("Close")
    .toggleClass("active");
});

When I select the word "Email" which has the class "email-slide" the top panel slides down, and the word "Email" turns to white, and the word "Email" turns into the word "Close".

All good so far. But when clicking "Close" though the color and panel go back to normal, the word "Close" does not turn back into the word "Email". Instead of .text("Close") I tried .toggleText("class") but it seems that does not work. Is there something similar I could do it accomplish it by adding the least amount of code possible? Thank you!

UPDATE - I am able to accomplish it by using the following code, but was hoping that would be a more efficient/shorter way of doing it. If not, let me know. Thanks!

$(".email-slide").click(function(){
    $("#panel").slideToggle("slow");
    $(this).toggleClass("active");
});

$(".email-slide").toggle(function (){
    $(this).text("Close")
}, function(){
    $(this).text("Email")
});
like image 661
cchiera Avatar asked Dec 01 '10 17:12

cchiera


People also ask

What is toggle () in jQuery?

The toggle() method attaches two or more functions to toggle between for the click event for the selected elements. When clicking on an element, the first specified function fires, when clicking again, the second function fires, and so on. Note: There is also a jQuery Effects method called toggle().

How do you add text on toggle switch?

Toggle Switch Text You can display additional text with the toggle switch by adding the toggle-switch-text class to the text element. Use the toggle-switch-text-left and toggle-switch-text-right classes to position the text on the left and right side of the toggle switch, respectively.


2 Answers

You could try:

$(".email-slide").click(function() {
    $("#panel").slideToggle("slow");

    $(this).toggleClass("active");

    if ($(this).text() == "Close")
       $(this).text("Email")
    else
       $(this).text("Close");

});

Or instead of comparing the text() value, you can also test for $(this).hasClass("active").

H.t.h. :)

like image 70
Kos Avatar answered Sep 28 '22 11:09

Kos


You don't have anything that sets the text back to 'Email'. There isn't a toggle method for content. You will have to do a test and set the value accordingly.

$(".email-slide").click(function(){
    $("#panel").slideToggle("slow");
    var text = $(this).text() == 'Email' ? 'Close' : 'Email';
    $(this)
    .text(text)
    .toggleClass("active");
});
like image 29
MacAnthony Avatar answered Sep 28 '22 12:09

MacAnthony