Trying to understand the concepts behind javascript event handlers -
as beginner in javascript, 1 confused
addeventlistener()
function, opposed use of
variable.onclick
here code testing with
/* * simple function swap text of 2 elements */ function swapfunction(){ var sitetitle = document.getelementbyid("site_title"); var sitetext = document.getelementbyid("site_text"); var temp = sitetitle.innerhtml; sitetitle.innerhtml = sitetext.innerhtml; sitetext.innerhtml = temp; return false; } /* * function handle page load */ function fullyloaded(){ var testevent = document.getelementbyid("test_click"); /* * why line has been commented out not work * yet line beneath does? */ //testevent.addeventlistener("click", swapfunction(), false); testevent.onclick = swapfunction; } window.onload = fullyloaded;
html
<html> <head> <title>this test application</title> </head> <body> <h1 id="site_title">welcome site</h1> <p id="site_text">this test site practicing on</p> <a id="test_click" href="#">test click</a> </body> </html>
please explain concept of event handlers , addeventlistener() or attachevent() in ie
thanks in advance
change
testevent.addeventlistener("click", swapfunction(), false);
to
testevent.addeventlistener("click", swapfunction, false);
because when write braces () after function name, executes immediately, wanna pass function argument. when use braces, not pass function, pass return value.
good luck in js learning!
Comments
Post a Comment