I was transferring all my JavaScript code to external file :
One of the inline codes were like this :
onclick="nextPrev(-1)" ; onclick="nextPrev(1)"
The method I tried was :
document.getElementById("nextPrev").addEventListener("click", nextPrev(1))
document.getElementById("nextPrev").addEventListener("click", function(){nextPrev(1)})
The second line of code works fine, i.e, triggered on the click of button. While the first code is a type of automatic (means value is shown without any click event).
So wanted to know the difference between both method I used in external file. Also if there is any other method to write onclick="nextPrev(1)" in external file please feel free to point out.
Here is a working snippet :
function nextPrev(e){
document.getElementById("demo").innerHTML = e;
}
document.getElementById("nextBtn1").addEventListener("click", nextPrev1(1))
function nextPrev1(e){
document.getElementById("demo1").innerHTML = e;
}
document.getElementById("nextBtn2").addEventListener("click", function() {
nextPrev2(1)
})
function nextPrev2(e){
document.getElementById("demo2").innerHTML = e;
}
<button type="button" id="nextBtn" onclick="nextPrev(1)">onclick="nextPrev(1)"</button>
<div id="demo"></div>
<button type="button" id="nextBtn1">func(var)</button>
<div id="demo1"></div>
<button type="button" id="nextBtn2">function(){func(var)}</button>
<div id="demo2"></div>
Thanks for help in advance
document.getElementById("nextPrev").addEventListener("click", nextPrev(1))
This will call nextPrev(1) immediately (hence giving the impression that the event is executed immediately) and set its returned value as the event listener callback.
document.getElementById("nextPrev").addEventListener("click", function(){nextPrev(1)})
This will set the event listener callback to a function which calls nextPrev(1) whenever the event is executed. Whenever the event is fired, the function is called, and only then is nextPrev(1) called.
The difference is as simple as illustrated below:
function callme(){
console.log("hello");
}
//Does not run until callmeWrapper is executed
function callmeWrapper(){
callme();
}
//Runs automatically
callme();
The second argument of addEventListener has to be the function that is supposed to run.
In this case :
document.getElementById("nextPrev").addEventListener("click", function(){nextPrev(1)})
when you are wrapping in a function definition, the nextPrev function is not run. Here when this line is encountered in the code, the wrapper function is attached as an event handler.
In this case,:
document.getElementById("nextPrev").addEventListener("click", nextPrev(1))
you are not attaching anything.
Here as soon as this line is encountered in the code, the function is run. And the return value(undefined by default) is assigned as an event handler. That will do nothing on click.