Baksa Gimm Baksa Gimm - 5 years ago 89
Javascript Question

why does this code execute my function soon as the document is loaded?

I'm trying to understand why this code below executes my function as soon as the document is loaded:

var list = document.getElementsByTagName('li');
function yep() {
window.alert('yep');
}
list[0].onclick = yep();


But this does not:

list[0].onclick = yep;


Why does
()
make a difference when executing a function in this situation?

Answer Source

The parenthesis () execute function immediately. On your second line you are assigning the value of list[0].onclick to the function name but not executing it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download