2

This works:

HTML:

<div id="mydiv">Help!</div>

CSS:

div {
    background-color: red;
}

Jquery:

function myfunction( c1 ) {
    $("#mydiv").css({'background-color': 'blue' });
}

$("#mydiv").on('click',  myfunction );

I understand that using () immediately after a function calls that function.

So...

How can I bind a function to a click, and pass parameters at the same time?

HTML:

<div id="mydiv">Help!</div>

CSS:

div {
    background-color: red;
}

Jquery:

function myfunction( c1 ) {
    $("#mydiv").css({'background-color': c1 });
}

$("#mydiv").on('click',  myfunction("blue") );

2 Answers 2

3

You can wrap the call in a function expression, and use the call method to set the context for the call as the context in the event handler:

$("#mydiv").on('click', function(){ myfunction.call(this, "blue"); });
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I was messing around with a fiddle trying to get this to work before i realized i didn't have a jquery library selected. Your answer works, and for future readers i'll say that this also works . . . . . . . . . . . . . . .$("#mydiv").on('click', function(){ myfunction("blue") });
@RedBeardPro: Yes, that works as long as you don't use this in the function to access the element where the event happened.
0

The jquery on event binding function has a 'data' parameter. .on( events [, selector ] [, data ], handler )

http://jsfiddle.net/aNDgC/101/

$('#myButton').on("click", {name: "world"} , function(event){
    $('#divOutput').html(event.data.name);
});

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.