0

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

2
  • why don't you want to call the function the second way? Commented Dec 5, 2014 at 12:13
  • 2
    @roryok because that works....;D Commented Dec 5, 2014 at 12:15

3 Answers 3

4

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Frankly speaking i never knew it...Thanks for sharing.
To pass data to a non-delegated event handler, you need a null placeholder as the second (selector) argument. As indicated in the doco. .on('keyup', null, 'a', myFunction)
@nnnnnn: Handy to know, I have adjusted the answer to include that version. Thanks :)
0

You can do it like this:

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

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

You'll basically create a function that always uses data to call the alert function.

You could also re-use it easily

$(".element").on('keydown', myFunction('b'));

Comments

0

jQuery expects a callback function. You can pass your function as argument like:

function my_fx(data){
    console.log(data)
}

$(".elem").on("keyup", my_fx); // data argument will be a jQuery Event object

But if you need custom information you can do a closure like this:

function make_fx(custom_data){
    return function(jquery_event){
        console.log(custom_data);
    }
}

$(".elem").on("keyup", make_fx("foo"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.