0
votes

The onFocus event keeps firing on page load and doesn't seem to work when the element goes into focus. I only want the alert to fire off when the the input comes into focus not on page load

//Input
var input = document.getElementById('phonenumber');
//onfocus execute function
input.onFocus = alert('test')
1

1 Answers

2
votes

You're calling the function alert and assigning its return value (undefined) to the focus handler. Try this instead:

input.onfocus = function() { alert('test'); };

Or, perhaps more understandably:

function inputFocused() {
    alert('test');
}
input.onfocus = inputFocused;

Note that there are no parentheses after inputFocused in the assignment. We want to set onfocus to the function itself, not to the result of calling the function.