0

I am making an application where I need to add functions in javascript. I am confused between between EventListener

document.querySelector('.foo').addEventListener('click',function(){
    alert('you clicked!')
})

Vs

Onlick

document.querySelector('.foo').onclick = function(){
    alert('you clicked!')
}

Vs

inline Functions where it is called in html

<button onclick="you_clicked();">Click Here</button>

I want to know which one is best suited for a multi page e-commerce like website.I have one javascript file where I write the functions and call them.

PROBLEMS THAT I FACE

1.whenever I use addEventListener or onclick methods, It shows errors if the eventlistener is on some other page.Like this

function.js:15 Uncaught TypeError: Cannot read property 'addEventListener' of null at myFunction.js:15

So I want to know how to avoid them. One thing I learned is to use something like this

if(document.querySelector('.foo')){
    document.querySelector('.foo').addEventListener('click',function(){
        alert("You Clicked!")
    })
}

Is this optimal and best practice ? Do I have to remove the eventListener as sometime it add load to the browser?

2.I have read it somewhere that calling functions from html is a bad practice .. just want to as is it the case ?

This can be easily done with using frameworks like jQuery however I want to write code on vanilla javascript.

I want to make a secure and optimal app so need advice from you guys. Thank you in advance ..

  • When you need to attach more than one event to an object, use `addEventListener` because `onClick` overrides what's there. You should initialize your business logic in separate files and call them when you need them so they aren't undefined. I would initialize the events in JS to keep them in a central location instead of having to look through html to see where the event is being attached. – Train Jan 31 '20 at 17:12
  • More reading https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick – Train Jan 31 '20 at 17:13
  • More reading https://stackoverflow.com/questions/42388436/add-event-listener-of-a-method-present-in-another-js-file – Train Jan 31 '20 at 17:14

0 Answers0