Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle script in jQuery 1.9.1

I just upgraded a site to 1.9.1 and the scipt below dont work anymore:

Script

$(document).ready(function(){
    $("#button").toggle(function() {
        $(this).text('Hide content');
    }, function() {
        $(this).text('Show content');
    });
    $('#button').click(function(){
       $("#content_div").slideToggle("medium");
    });
});

HTML

<a href="#" id="button">Show content</a>

I am not so good at jQuery so I hope somebody can help me with this script, I´ll appreciate if a answer contains a explanation of the solution (trying to learn jQuery).

Thanks!


1 Answers

This functionality of .toggle was removed in jQuery 1.9

There are a variety of ways to handle this. One is to simply keep track of the click state of the object internally.

$("#button").on('click', function () {
    if ($(this).data('clicked')) {
        //functionality state 2
    }
    else {
        //functionality state 1
    }
    $(this).data('clicked', function (_, data) { return !data; });
});

You can even manage more than two states using integers and modulo.

like image 103
Explosion Pills Avatar answered Feb 23 '26 21:02

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!