javascript - What is wrong with my code for assigning onfocus event to the element? -


i have following code tried assign onfocus event element, whenever element gets focused, call alert. however, alert appears when page loaded, , never after that.

<html> <head> </head> <body onload = "loadings();"> <div>        <form>           <input type="text" id="foo"/>     </form> </div>  <script type="text/javascript"> function loadings(){     document.getelementbyid("foo").onfocus = alert("foo");  } </script> </body> </html> 

please note can't <input type="text" id="foo" onfocus="alert('foo')"/> thing trying achieve.

also should work in firefox, chrome, ie, safari.

thanks in advance!

this code:

document.getelementbyid("foo").onfocus = alert("foo"); 

assigns result of calling alert() onfocus property. meant is:

document.getelementbyid("foo").onfocus = function(){ alert("foo"); }; 

this using dom level 0 event model can have 1 handler per event. if want more flexible while still cross-platform may try library abstract event model jquery does:

$('#foo').focus(function(){ alert("foo"); }); 

that way don't have worry attachevent in ie vs. addeventlistener in else, if need simple case in example level 0 model fine , works across browsers.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -