Reputation: 3763
I don't get it. Why does this alert on page load? How to make it alert only "onfocus"?
<input id="mail" name="E-post" value="E-post">
<script>
window.onload = function () {
function onfocusFunction() {
alert('Why!?');
}
var myMail = document.getElementById('mail');
myMail.onfocus = onfocusFunction();
}
</script>
Upvotes: 0
Views: 1713
Reputation: 48793
With parenthesis ()
, you are calling onfocusFunction
function and assigning undefined
to myMail.onfocus
:
myMail.onfocus = undefined;
as your onfocusFunction
function does not return anything.
Without parenthesis, you will have onfocusFunction
object, which should be assigned to .onfocus
:
myMail.onfocus = onfocusFunction; //No parenthesis before ';'
UPDATE: If you want to pass parameters either, then try like this:
function onfocusFunction(param1,param2) {
return function(){
alert(param1+":"+param2);
};
}
var myMail = document.getElementById('mail');
myMail.onfocus = onfocusFunction("value1","value2");
Then when onfocus
event will be triggered you will see "value1:value2"
as an alert.
Upvotes: 2
Reputation: 21472
when you type myMail.onfocus = onfocusFunction();
onfocusFunction()
and myMail.onfocus
( in this case the return value is null );
let say :
function onfocusFunction() {
alert('Why!?');
return "ok";
}
so myMail.onfocus
will be the string 'ok' instead of a function
you can use Engineer's Solution
or try :
myMail.onfocus = function(){alert("why")};
Upvotes: 0