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 ..