简体   繁体   中英

jQuery toggle alternative way?

Since toggle is deprecated I used this to toogle div:

$("#syndicates_showmore").on("click", function () {

    if (!clicked) {
        $('#syndicates').fadeTo('slow', 0.3, function () {
            $(this).css(
            {
                'height': 'auto',
                'overflow': 'none'
            });
        }).fadeTo('slow', 1);

        setTimeout(function () {
            $("#syndicates_showmore").text("Show less");
        }, 500);

        clicked = true;
    }
    else {
        $('#syndicates').fadeTo('slow', 0.3, function () {
            $(this).css(
            {
                'height': '290px',
                'overflow': 'hidden'
            });
        }).fadeTo('slow', 1);

        setTimeout(function () {
            $("#syndicates_showmore").text("Show more");
        }, 500);

        clicked = false;
    }
});

Is there any cleaner way to do this?

According to the jQuery 1.9 Upgrade Guide :

.toggle(function, function, ... ) removed

This is the "click an element to run the specified functions" signature of .toggle() . It should not be confused with the "change the visibility of an element" of .toggle() which is not deprecated. The former is being removed to reduce confusion and improve the potential for modularity in the library. The jQuery Migrate plugin can be used to restore the functionality.

In other words, you can still use .toggle like this:

var clicked = false;
$("#syndicates_showmore").on("click", function () {
    clicked = !clicked;
    var showText = "Show " + (clicked ? "more" : "less");
    $('#syndicates').toggle(function () {
        $("#syndicates_showmore").text(showText);
    });
});

The best alternative is to use .toggleClass() :

$("#syndicates_showmore").on("click", function () {
    $('#syndicates').toggleClass("newClass, 1000", "easeInOutBounce")
});

jQuery .toggleClass() API Documentation :

Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

If using with jQuery UI you can easily animate it with using different easing options.

Easings:

Easing functions specify the speed at which an animation progresses at different points within the animation. jQuery UI provides several additional easing functions, ranging from variations on the swing behavior to customized effects such as bouncing.

Example online

Taken from jQuery API

$("#clickme" ).click(function() {
   $( "#book" ).toggle( "slow", function() {
     // Animation complete.
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM