I'm learning about Javascript event listeners.
If you say click_01(), click_02(), click_03(), as shown in the source code below, the button is clicked without pressing the button.Why?
<body>
<input id="Button1" type="Button" value="Button"/>
<input id="Text1" type="text"/>
<divid="output"></div>
<script type="text/javascript">
window.onload=function(){
var button= document.getElementById("Button1");
button.addEventListener('click', click_01(), false);
button.addEventListener('click', click_02(), false);
button.addEventListener('click', click_03(), false);
}
function click_01(){
var text = document.getElementById("Text1");
text.value=" button clicked.";
}
function click_02(){
var text = document.getElementById("output");
text.innerHTML=" button clicked.";
}
function click_03(){
window.top.document.title=" button clicked.";
}
</script>
</body>
Hello,
<body>
<input id="Button1" type="Button" value="Button"/>
<input id="Text1" type="text"/>
<divid="output"></div>
<script type="text/javascript">
window.onload=function(){
var button= document.getElementById("Button1");
button.addEventListener('click', click_01, false);
button.addEventListener('click', click_02, false);
button.addEventListener('click', click_03, false);
}
function click_01(){
var text = document.getElementById("Text1");
text.value=" button clicked.";
}
function click_02(){
var text = document.getElementById("output");
text.innerHTML=" button clicked.";
}
function click_03(){
window.top.document.title=" button clicked.";
}
</script>
</body>
This should work as expected.
button.addEventListener('click', click_01, false);
button.addEventListener('click', click_02, false);
button.addEventListener('click', click_03, false);
This part is important to register click_0n
in the second argument as a function to call when a click event comes to button.
This is
button.addEventListener('click', click_01(), false);
button.addEventListener('click', click_02(), false);
button.addEventListener('click', click_03(), false);
If this is the case, the return value of click_0n()
will be used to register functions to be called when a click event occurs in Button.
It's a common mistake.
Correctly
button.addEventListener('click', click_01, false);
button.addEventListener('click', click_02, false);
button.addEventListener('click', click_03, false);
That's it.
click_01()
is a function call because it has parentheses.
© 2024 OneMinuteCode. All rights reserved.