Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Toggle text to change on click

I have a menu button, which when clicked will slide down a div below.

My menu is title "+ Open menu"

When the menu button is clicked my code changes the title to "+ Menu" to indicate that the menu is open.

When the user closes the menu I would like the title to revert back to "- Menu"

This is my HTML which defines the class, test in this case.

<span class="test">+ Open menu</span>

Here is my jQuery function, I cannot figure out how to revert the menu state.

$(document).ready(function () {
$(".widget_head_type").click(function () 
{
    $(".widget_body_type").slideToggle("slow");
    $(".test").text("- Close menu");
});

});

like image 822
BallSoHard Avatar asked Dec 12 '22 07:12

BallSoHard


2 Answers

$(".widget_head_type").click(function () {
    $(".widget_body_type").slideToggle("slow");
    ($(".test").text() === "+ Open menu") ? $(".test").text("- Close menu") : $(".test").text("+ Open menu");
});
like image 136
Bitter Avatar answered Dec 26 '22 20:12

Bitter


jQuery.fn.extend({
    toggleText: function (a, b){
        var that = this;
            if (that.text() != a && that.text() != b){
                that.text(a);
            }
            else
            if (that.text() == a){
                that.text(b);
            }
            else
            if (that.text() == b){
                that.text(a);
            }
        return this;
    }
});

Use as:

$("#YourElementId").toggleText('After', 'Before');
like image 39
Diego Favero Avatar answered Dec 26 '22 20:12

Diego Favero