Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is using a variable in an onclick worse than using e.target?

Wondering if there is a performance/memory area I could improve when setting onclick listeners to elements.

Example:

let btn = document.querySelector('.example')
btn.addEventListener('click', (e) => {
    btn.classList.add('active');
    btn.onmouseleave = () => {
        console.warn('leave')
    }
})

compared to:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let btn = document.querySelector('.example')
btn.addEventListener('click', (e) => {
    e.target.classList.add('active');
    e.target.onmouseleave = () => {
        console.warn('leave')
    }
})

I would think that using btn would take a lot more work as the computer has to save the variable and remember it, whereas e.target uses the event temporarily. Which one is best for the least amount of memory consumption?

>Solution :

Event.target might not be your btn – to get your button (Element on which the handler is attached) use Event.currentTarget. Say you clicked an icon inside your button, the Event.target will be your icon.

There’s not much difference in performance other than perhaps engine implementations. btn is an element stored as variable which already is the currentTarget: btn === e.currentTarget // always true therefore it’s your choice. If I did not had already a btn cached Element I would go for the Event.currentTarget reference – otherwise there’s not much difference.

onmouseleave and other on* handlers should never be used unless you’re creating (in a really small and readable script) brand new Elements from in-memory. Use EventTarget.addEventListener() instead with the {once: true} argument option – if needed ().

Third, better version:

const addActive = (evt) => {
  const elBtn = evt.currentTarget;
  elBtn.classList.add("active");
  elBtn.addEventListener("pointerleave", () => {
    console.log("leave");
  }, {once:true})
};

// since you're using classes instead of ID,  
// make sure to refer to All your elements by class:
const elsBtns = document.querySelectorAll('.example');

elsBtns.forEach((elBtn) => {
  elBtn.addEventListener("click", addActive);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading