I have a function called showText()
which copies some text from form textbox to a paragraph elsewhere. It is called with the following:
document.getElementById("mybutton").onclick = showText;
It will not work if I add the () to the end of showText, which I understand from reading similar answers here is the only way to call a function.
Later in the script it requires the () to work:
window.addEventListener("keypress", function(e) {
var keycode = e.keyCode;
if (keycode == 13) {
showText();
}
}, false);
I'm not sure what is going on here.
showText
returns the function showText
.
showText()
runs the function showText
and returns the result.
When you attach a function to an event handler like .onclick, it is expecting a function
.
You can call a function and return the result to an event like this: document.getElementById("mybutton").onclick = showText();
provided the function itself returns a function:
function showText() {
return function () {
alert('hello world');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With