Ilja
Ilja

Reputation: 46479

Strange addEventListener behaviour

I'm working on a basic javascript form validation

var seUSer = document.getElementById("seUSername");
seUser.addEventListener("blur", validator(seUsername), false);

function validator (input) {
    if (input.value == "") {
        input.style.color="#fff";
    } else {
        input.style.color="#f0f0f0";
    }
}

In this case I'm expecting concrete input to change colour if it's value is empty after user has preformed "blur" action, so clicked away, but it changes colour on a page load i.e. without user doing anything, Is the "blur" action on the input by default? or what would be a right approach to handle this situation.

here is jsFiddle: http://jsfiddle.net/Z4K6D/

As you can see field is red from the beginning, but it should only be red if user un-focuses it and there is nothing in it.

Upvotes: 1

Views: 32

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

This code:

loginUsername.addEventListener("blur", validateForm(loginUsername), false);

is calling validateForm and passing the return value of it into addEventListener, exactly the way foo(bar()) calls bar and passes its return value into foo. You're not setting it up as an event handler.

To set up a function as an event handler, you don't call it, you just pass a reference to it. Since you want to give your function an argument, to do that in this case you'd wrap a function around it:

loginUsername.addEventListener("blur", function() {
    validateForm(loginUsername);
}, false);

Alternately, make your validateForm function work with this rather than the input argument:

document.getElementById("loginUsername").addEventListener("blur", validateForm, false);
// Note no (), we're not calling it ------------------------------------------^

function validateForm () {
    if (this.value == "") {
        this.style.background="#f26060";
    } else {
        this.style.background="#fff";
    }
}

...because within the event handler hooked up via addEventListener, this is set to the element on which you hooked the event.

Upvotes: 3

Related Questions