Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .on keyup and blur firing onload only

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/

like image 589
Mooseman Avatar asked May 20 '13 16:05

Mooseman


3 Answers

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

like image 70
Claudio Redi Avatar answered Dec 07 '22 23:12

Claudio Redi


You're not declaring the functions as callbacks, you're executing them and their return result is assigned as a callback (which doens't work).

Try this:

  $('#input1').on({
    keyup: function() { myFunction('keyup') },
    blur: function() { myFunction('blur') },
    focus: function(){console.log('focus!');}
  });
like image 27
Nick Andriopoulos Avatar answered Dec 08 '22 00:12

Nick Andriopoulos


You need to pass a function as an argument.. you are passing the return value of the called function

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

Or you can convert your myFunction to a function generator

function myFunction(text){
   return function(){
       console.log(text);
   }
}

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

Demo at https://jsfiddle.net/gaby/GrMQX/6/

like image 37
Gabriele Petrioli Avatar answered Dec 08 '22 01:12

Gabriele Petrioli