Search code examples
javascriptjquerybindonkeyup

Execute JavaScript function when using jQuery on event


I want to load a function when an on event is triggered.

I have this code but it doesn't work.

    function myFunction(data){
        alert(data);
    }

    $(".element").on('keyup', myFunction('a'));

I do not want to call the function like this:

    $(".element").on('keyup', function(){
         myFunction('a');
    });

How do I make this work? Peter


Solution

  • The delegated version of on allows data to be passed as well as the function:

    $(document).on('keyup', ".element", 'a', myFunction);
    
    function myFunction(e){
        alert (e.data);
    }
    

    JSFiddle: http://jsfiddle.net/TrueBlueAussie/kqLqvgp9/2/

    Note: It should be possible to pass data with the non delegated on handler, but it confuses the 'a' parameter as a selector and thinks it is delegated anyway.

    As nnnnnn points out, you can replace the selector with null if you do not want a delegated event handler:

    JSfiddle: http://jsfiddle.net/TrueBlueAussie/kqLqvgp9/5/

    $('.element').on('keyup', null, 'a', myFunction)
    
    function myFunction(e){
        alert (e.data);
    }