Haris Z
Haris Z

Reputation: 119

Pass params to function when using on() in jquery

A senior of mine advise me to always write using snytax 2, but I have some issue with passing parameters. If my function coloring has 2 params, how I pass them in?

//snytax 1
$("body").on("li","click",function(){
    $(this).css({'color:red'});
});

//snytax 2
$("body").on("li","click", coloring);

function coloring(param1,param2){
//what to do here?
} 

Upvotes: 2

Views: 47

Answers (1)

Sandeep Nayak
Sandeep Nayak

Reputation: 4757

You can use event.data like below:

Sample code:

$(document).ready(function() {
  $(".btn").on("click", {
    a: 1,
    b: 2
  }, callme);

});

function callme(event) {
  var data = event.data;
  alert(data.a)
  alert(data.b)

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Click me!</button>

In case you were wondering if you can directly do this:

 $(".btn").on("click", callme(a,b)); // This would call the function when the event is bound. So, even without the click the function is invoked.

Upvotes: 4

Related Questions