1

so this is my function for adding and removing but it only work for adding it doesnt remove on again click

(function ($) {
      $(".call-us-button .call").on("click", function () {
        $(this).parent().find(".phone-number").fadeIn();
        $(this).parent().find(".qr-code-call").fadeIn();
        $(this).parent().addClass("callBtnActive");
      });
    
      $(".call-us-button .call").on("click", function () {
        $(this).parent().find(".phone-number").fadeOut();
        $(this).parent().find(".qr-code-call").fadeOut();
        $(this).parent().removeClass("callBtnActive");
      });
    })(jQuery);
1
  • 1
    Use one click event handler and use hasClass to determine whether to fade in or out and whether to add or remove the class. Commented Jun 28, 2022 at 14:00

1 Answer 1

1

You can achieve what you need in a single event handler by using the toggleClass() and fadeToggle() methods. In addition the code can be made more succint by chaining the methods and merging the class selectors.

(function($) {
  $(".call-us-button .call").on("click", function() {
    $(this).parent()
      .toggleClass("callBtnActive")
      .find(".phone-number, .qr-code-call").fadeToggle();
  });
})(jQuery);

As an aside, note that your code is wrapped in an IIFE, not a document.ready event handler. The two are not equivalent. It seems like your code is at least running so it's in the correct place in the DOM, but be aware this may not always be the case.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, fadeToggle, I did not know that one. I thought I was clever with [active ? "fadeOut" : "fadeIn"]()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.