4

Fiddle

So I'm having this problem.

I have a simple form:

<form method="post" action="login.php">

<input type="text" name="Username" value="Username" />
<input type="password" name="Password" value="Password" />
<input type="submit" name="submit" value="Log in" />

</form>

And this script:

function focus(element) {

    console.log('focused ' + element.getAttribute('name'));

    var elementValue = element.value;
    var elementName = element.getAttribute('name');
    elementValue = (elementValue == elementName ? '' : elementValue);

}


var fields = ['Username', 'Password'];

for (var i = 0; i < fields.length; i++) {

    console.log(i + ': ' + fields[i]);

    var input = document.getElementsByName(fields[i])[0];

    console.log('input value: ' + input.value);

    input.onFocus = focus(input);

}

It is supposed to create Focus event listeners for every of the inputs and call focus() function as user clicks on any of the fields. But for some reason, as console shows, it just calls the function once a loop for every of the fields and just stops not responding to future Focus events.

So my guess is there's something wrong with this line input.onFocus = focus(input);, but I don't know what. What am I missing?

Ivan Chepurin
  • 131
  • 1
  • 2
  • 10

2 Answers2

0

On the line below, you're calling the focus function immediately and passing the return value (which is undefined). You also need to use onfocus not onFocus because the property name is case sensitive.

input.onFocus = focus(input);

Instead, you can use .bind() like so:

input.onfocus = focus.bind(null, input);

This will setup the function with the argument set, without actually calling it.

Updated fiddle

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Ok, thank you. I need to learn about this bind() method though, cause I don't quite understand the mechanics. – Ivan Chepurin Apr 20 '15 at 16:38
  • No problem, glad it helped. Click on the link I provided to `.bind()`, the MDN docs explain it really well, but basically it allows you to assign a function which has its this context and argument list pre-configured, without actually calling it. – MrCode Apr 20 '15 at 16:40
  • Yep. Now I got it. Took a minute. – Ivan Chepurin Apr 20 '15 at 16:45
0

Because instead of assigning the focus function as the handler of the onFocus event, you're assigning its returned value (which is undefined).

Try this instead:

input.onfocus = focus.bind(input, input);

Or

input.onfocus = function() { focus(input);

Also, you need to change onFocus to onfocus.

See MDN

haim770
  • 48,394
  • 7
  • 105
  • 133