user2190690
user2190690

Reputation: 2044

jQuery: .on() using events in a plain object to reference one function

I find the presentation/style of the following jQuery .on() preferable (ie handing over a plain object that can contain multiple events/callbacks):

$( selector ).on( {  mouseover:function(event) {
                       console.log('mouseover');
                     },
                     mouseout:function(event) {
                       console.log('mouseout');
                     }
                   });

However I would like both mouseover and focus to reference the same function so I tried the following:

$( selector ).on( {  'mouseover, focus':function(event) {
                       console.log('over/focus');
                     },
                     'mouseout, focusout':function(event) {
                       console.log('mouseout/focusout');
                     }
                   });

The results were focus and focusout worked but not mouseover/mouseout.

Could anyone guide me on how to do this inside a plain object, ie with this structure/style of using .on()

Many thanks in advance

Upvotes: 0

Views: 142

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075159

From the documentation:

An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).

(my emphasis)

So lose the commas:

$( selector ).on( {  'mouseover focus':function(event) {
// No comma -------------------^
                       console.log('over/focus');
                     },
                     'mouseout focusout':function(event) {
// No comma ------------------^
                       console.log('mouseout/focusout');
                     }
                   });

Or of course, use named functions.

Here's an example using events that are unrelated to each other (for clarity):

$("#the-element").on({
  "change click": function(e) {
    $("<p>").text("Got " + e.type).appendTo(document.body);
  }
});
<input type="text" id="the-element">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 3

Related Questions