7

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/

Syscall
  • 19,327
  • 10
  • 37
  • 52
Mooseman
  • 18,763
  • 14
  • 70
  • 93

5 Answers5

13

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

Syscall
  • 19,327
  • 10
  • 37
  • 52
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
6

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!');}
  });
Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
6

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/

Syscall
  • 19,327
  • 10
  • 37
  • 52
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • Is returning the function going to be slower than calling the anonymous function? – Mooseman May 20 '13 at 16:52
  • 1
    there is a negligible overhead once when you bind the event handlers.. after that the actual event handling is exactly the same. But it solves the issue of passing a parameter when binding .. (*and not repeating the body function for each event you want to handle..*) – Gabriele Petrioli May 20 '13 at 17:06
4

You're actually executing the functions when you call them that way. Try this:

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

JSFiddle example

Syscall
  • 19,327
  • 10
  • 37
  • 52
j08691
  • 204,283
  • 31
  • 260
  • 272
0

use with .on() Event

$(document).on("keyup blur", "#input1", function(event)
    {       
    // your code        

    });
Yasir Aslam
  • 477
  • 1
  • 5
  • 9