0

I do an animation button with CSS3 that will change the burger to the cross when clicking. How to convert code from pure JS to jQuery?

var toggles = document.querySelectorAll(".cmn-toggle-switch");

for (var i = toggles.length - 1; i >= 0; i--) {
    var toggle = toggles[i];
    toggleHandler(toggle);
};

function toggleHandler(toggle) {
    toggle.addEventListener( "click", function(e) {
        e.preventDefault();
        (this.classList.contains("active") === true) ? this.classList.remove("active") : this.classList.add("active");
    });
}
5
  • 1
    Why do you want something like that? Does your code have errors that you are insisting on using jQuery? Your code looks clean as it is. Commented Dec 1, 2017 at 13:09
  • 1
    I think $(".cmn-toggle-switch").onClick(() => { $(this).toggleClass("active") }); this will do Commented Dec 1, 2017 at 13:12
  • i think he wants less code Commented Dec 1, 2017 at 13:24
  • @AswinRamesh that won't work for several reasons ... there is no onClick in jQuery and no this in arrow functions Commented Dec 1, 2017 at 13:25
  • Oh I forgot... @charlietfl it should be like $(".cmn-toggle-switch").click(function() { $(this).toggleClass("active"); }); right? Commented Dec 1, 2017 at 13:29

1 Answer 1

4

There you go.

var toggles = $('.cmn-toggle-switch');

toggles.on('click', function(e){

      e.preventDefault();
      $(this).toggleClass("active");

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

1 Comment

@AdamAzad i can not because of the level of reputation. I created an account a couple of days ago.

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.