Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use parentheses with javascript function [duplicate]

Tags:

javascript

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.

like image 782
Russell Avatar asked Apr 02 '13 22:04

Russell


1 Answers

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'); 
    }
}
like image 78
Daniel Imms Avatar answered Nov 14 '22 21:11

Daniel Imms