jQuery .on keyup and blur firing onload only

Mooseman picture Mooseman · May 20, 2013 · Viewed 22.5k times · Source

Problem: The blur and keyup events each fire once onload, and only onload. How can I get them to work correctly?

jQuery:

function myFunction(text){
    alert(text);
}
$('#input1').on({
    keyup: myFunction('keyup'),
    blur: myFunction('blur'),
    focus: function(){console.log('focus!');}
});

Fiddle: https://jsfiddle.net/GrMQX/

Answer

Claudio Redi picture Claudio Redi · May 20, 2013

You are not assigning a function to keyup and blur, you're assigning the result of the execution of myFunction.

Change it like this:

$('#input1').on({
    keyup: function() { myFunction('keyup'); },
    blur:  function() { myFunction('blur'); },
    focus: function() { console.log('focus!'); }
});

DEMO