turkyoung
turkyoung

Reputation: 11

toggle class on click jquery

i have this code and i am trying to add and remove class when chat button is clicked.

live url is here. https://itsneotpras.myshopify.com/

when chatbox is clicked then bounceUp99 class is added and it works as expected and when that chat icon is clicked again it is removed but that moment i want to remove bounceUp99 and add class bounceDown99. below is my code. i have commented out codes which i have removed. any help will be great. if bounceDown99 is added when clicked again then chat box should close with some animation. you can see that by manually replacing bounceUp99 with bounceDown99 when chat box is opened

 jQuery("#pushdaddy-button,#pushdaddy-close").click(function() { 
// jQuery("#pushdaddy-box").removeClass("bounceDown99");
              // jQuery("#pushdaddy-box").addClass("bounceUp99");
              if(jQuery("#pushdaddy-box").hasClass('bounceDown99')) {
    //    jQuery("#pushdaddy-box").removeClass('bounceDown99');
        //        jQuery("#pushdaddy-box").addClass('bounceUp99');

          //     jQuery("#pushdaddy-box").removeClass('bounceUp99');


    } 
    else if(jQuery("#pushdaddy-box").hasClass('bounceUp99')) {
               jQuery("#pushdaddy-box").removeClass('bounceUp99');
  //    jQuery("#pushdaddy-box").addClass('bounceDown99');

    }
    
    else {
       jQuery("#pushdaddy-box").addClass('bounceUp99');
              jQuery("#pushdaddy-box").removeClass('bounceDown99');

    }



            })

Upvotes: 1

Views: 146

Answers (2)

Danielprabhakaran N
Danielprabhakaran N

Reputation: 585

Toggle Class will work if you have the 'bounceUp99' class as default.

$(element).toggleClass("bounceUp99 bounceDown99");

This will remove class bounceUp99 and add the class bounceDown99. If you do that again, it will remove class bounceDown99 and reinstate class bounceUp99.

If you want to match the elements that expose either class, you can use a multiple class selector and write:

$(".bounceUp99, .bounceDown99").toggleClass("bounceUp99 bounceDown99");

But here, We can't have bounceUp99 class as default. so, we can use hasClass,addClass and removeClass

$("h1").on("click", function () {
      if ($(this).hasClass("a")) {
        $(".a").addClass("b").removeClass("a");
      } else if ($(this).hasClass("b")) {
        $(".b").addClass("a").removeClass("b");
      } else {
        $(this).addClass("a");
      }
    });

Demo: https://codesandbox.io/s/optimistic-sunset-74gns?file=/index.html

Upvotes: 0

The Anonymous Koder
The Anonymous Koder

Reputation: 602

There is a toggleClass method to do this.
You can learn more about it in the official documentaion.

<div onclick = "jQuery(this).toggleClass('my-class')">div tag</div>

Note: Consider using $('selector') instead of jQuery('selector').

Upvotes: 2

Related Questions