Search code examples
javascriptonfocus

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


I have a following code which I tried to assign onfocus event to the element, so that whenever the element gets focused, call alert. However, alert only appears when the page loaded, and 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 that I can't do <input type="text" id="foo" onfocus="alert('foo')"/> for the thing I am trying to achieve.

Also this should work in Firefox, Chrome, IE, Safari.

Thanks in advance!


Solution

  • This code:

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

    assigns the result of calling alert() to the onfocus property. What you meant is:

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

    This is using the DOM Level 0 event model where you can only have one handler per event. If you want something more flexible while still cross-platform then you may try some library to abstract the event model for you like jQuery does:

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

    That way you don't have to worry about attachEvent in IE vs. addEventListener in everything else, but if you only need the simple case like in your example then the Level 0 model is perfectly fine and works across all browsers.