-1

How can I pass a parameter in a call like the following?:

$('nav .navbar-nav .level-0').on('mouseenter', toggle_level0_menu);

function toggle_level0_menu(/*parameters*/) {
  // code here
}

If toggle_level0_menu needed to received a parameter, is there a way to pass it from an inline call? I know the following is a solution:

$('nav .navbar-nav .level-0').on('mouseenter', function() {
  // code here
});

But this is precisely what I want to avoid if possible.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Sebastian
  • 845
  • 4
  • 12
  • 25

4 Answers4

4

YES it's possible

To pass parameters to a jQuery event handler. Pass a data object as the second argument on the event, the contents of the object will be transferred onto the data variable of event.

Check the working example bellow.

Hope thi helps.


$('.level-0').on('mouseenter', {msg: 'test'}, toggle_level0_menu);

function toggle_level0_menu(e){
     console.log(e.data.msg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='level-0'>level-0</div>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • It works but not completely. I mean, the behavior is not exactly the same as wrapping the code into an anonymous function (the way I'm trying to avoid) – Sebastian Dec 18 '15 at 21:43
3

You have to wrap your function call in an anonymous function. If you pass parameters to a named function you are invoking it and the returned value will be passed in instead of the call back. So as you said:

$('nav .navbar-nav .level-0').on('mouseenter', function(){
   toggle_level0_menu(/*parameters*/);
});

EDIT:

If the parameters you wish to pass in to the callback come off the event, you can write the callback function toggle_level0_menu(/*parameters*/) so that it takes an event, and you can access the event data that way.

e.g.

function toggle_level0_menu(event) {
   console.log(event.target);
}

 $('nav .navbar-nav .level-0').on('mouseenter', toggle_level0_menu);

Look at the documentation for jquery on. You can also delegate to future DOM nodes as well as pass in event.data objects.

Sam Jacobs
  • 346
  • 1
  • 8
0

There isn't a situation that it would be possible to pass parameters into a function like that, as it's called by the window (which provides its own parameters to the function)

In the case that the function's behavior should vary, code it within the function.

Though look into .bind() .call() and .apply()

Andrue Anderson
  • 664
  • 4
  • 17
-1

You can pass data to the function using jquery on.

Also an example given here

$("#myid").on("click",myfunction.bind(this, arg1, arg2));
Community
  • 1
  • 1
gurvinder372
  • 66,980
  • 10
  • 72
  • 94