简体   繁体   中英

Replace classes within a click function

I need to replace some class names within a click function.

I have this line of code, which adds the correct class when a button is clicked:

showLeft.onclick = function() {
    $(".cbp-spmenu-open ul li.inview").toggleClass("animated bounceInLeft visible");
};

When I click the button again, how can I replace the above class names with the following: animated bounceOutLeft hidden and vice-versa?

You just want to replace visible with hidden and bounceIn with bounceOut

.toggleClass("bounceInLeft visible").toggleClass("bounceOutLeft hidden");

and use addClass for animated , which you want to keep.

See example fiddle

How about this:

showLeft.onclick = function() {
    if($(".cbp-spmenu-open ul li.inview").hasClass('hidden')) {
        $(".cbp-spmenu-open ul li.inview").toggleClass("animated bounceInLeft visible");
    } else {
        $(".cbp-spmenu-open ul li.inview").toggleClass("animated bounceOutLeft hidden");
    }
}

It checks whether your element is hidden or not and make it visible or not.

In your html (if possible) try to add bounceOutLeft and hidden to the li.inview element

If not add them with jquery on page load.

$(".cbp-spmenu-open ul li.inview").addClass("bounceOutLeft hidden"); // only when you can't edit the html
showLeft.onclick = function() {
  $(".cbp-spmenu-open ul li.inview").toggleClass("animated bounceOutLeft bounceInLeft visible hidden");
};

Like this:

showLeft.onclick = function() {
    if($(".cbp-spmenu-open ul li.inview").hasClass("hidden")
        $(".cbp-spmenu-open ul li.inview").toggleClass("animated bounceInLeft visible");
    else
       $(".cbp-spmenu-open ul li.inview").toggleClass("animated bounceOutLeft hidden");
};

Use this one

showLeft.onclick = function() {
    $(".cbp-spmenu-open ul li.inview").toggleClass('bounceInLeft visible').toggleClass('bounceOutLeft hidden');
};

or this :

showLeft.onclick = function() {
    var $li = $(".cbp-spmenu-open ul li.inview");
    if($li.hasClass('visible'))
        $li.removeClass('bounceInLeft visible').addClass('bounceOutLeft hidden');
    else
        $li.removeClass('bounceOutLeft hidden').addClass('bounceInLeft visible');
};

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