Miss A
Miss A

Reputation: 451

jQuery on() syntax

I have a newbie syntax question, here is my code:

$('.selector').on({
  mouseenter: function() {
    // ...
  },
  mouseleave: function() {
    // ...
  }
});

Now what if I wanted to bind the mouseenter and touchstart events to the same function? I know I can do this:

$('.selector').on('mouseenter touchstart', function(){
  // ...
});

But I like the look of my first example. (Am I right in thinking that it is only the syntaxt that differs in my examples?) Also does anyone know where I can look up these kind of things? The jQuery API only ever show one way writing things.

Upvotes: 0

Views: 481

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

Try it this way

 $('.selector').on({
       mouseenter : move,
       touchstart : move
   });

    function move(){

    }

If you want to define different functionalities to the two events go by this approach.

If the functionality is the same for both then your code should work..

Upvotes: 1

Alnitak
Alnitak

Reputation: 339816

If the two events bind to the same function, then bind them to the same function!

If you create two anonymous functions with identical bodies, you'll be using more memory than you need to because you will have actually created two separate functions.

In that sense, your two examples are not semantically identically.

Alternatively, declare the callback function once outside (i.e. not as an anonymous function) and use the first syntax:

var cb = function(ev) { ... }

$(el).on({
    mouseenter: cb,
    touchstart: cb
});

Upvotes: 4

Related Questions