0

Are any of these versions correct? I would like the icon to change after clicking the menu. in Javascript these are my beginnings and I don't know what is right

const menu = document.querySelector('#menu-btn');
menu.onclick = () => {
    menu.classList.toggle('fa-times');
    navbar.classList.toggle('active');
};

or this

const menu = document.querySelector('#menu-btn');
menu.addEventListener('click', function(event){
  menu.classList.toggle('fa-times');
  navbar.classList.toggle('active');
});
Jonathan Stellwag
  • 3,843
  • 4
  • 25
  • 50
Greemi
  • 1

1 Answers1

0

Both are correct, but there are several differences between onclick and addEventListener.

  1. addEventListener can add multiple events to a particular element. onclick can add only a single event to an element. It is basically a property, so gets overwritten.
  2. addEventListener can take a third argument that can control the event propagation. Event propagation cannot be controlled by onclick.
  3. addEventListener does not work in older versions of Internet explorer, which uses attachEvent instead. onclick works in all browsers.
ruleboy21
  • 5,510
  • 4
  • 17
  • 34