Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
toggle class on click with javascript on 2 ways, which is correct?

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');
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!