What is wrong with my code to assign an onfocus event to an element?

I have the following code that I tried to assign to the onfocus event for an element, so whenever the element becomes focused, raise a warning. However, a warning appears only when the page loads and never after.

<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 cannot do <input type="text" id="foo" onfocus="alert('foo')"/>for what I am trying to achieve.

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

Thanks in advance!

+3
source share
4 answers

This code:

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

assigns the result of calling alert () to the onfocus property. What did you mean:

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

DOM Level 0, . - , -, - , jQuery:

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

, attachEvent IE addEventListener , , , , 0 .

+5

rsp , , , . , rsp. .

function MyEventHandler ()
{
    alert("foo");
}

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

, , , (). , . , .

+2

You can use addeventlistener as below.

document.getElementById("foo").addEventListener("focus", function(){alert("foo")}, false);
0
source

Here's a generic function to add an event handler

function addEvent( obj, type, fn ){
    if(!obj){
        return;
    }
    if (obj.addEventListener){
        obj.addEventListener( type, fn, false );
    }
    else{
        if (obj.attachEvent){
            obj["e"+type+fn] = fn;
            obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
            obj.attachEvent( "on"+type, obj[type+fn] );
        }
    }
}

then

addEvent(document.getElementById('foo'),'focus',myEventhandler);
0
source

Source: https://habr.com/ru/post/1793206/


All Articles