Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Multiple Actions in jQuery on()

I am wondering if it is possible to combine multiple actions to the same on() function?

My code:

$(document).on('mouseout', '#tip', function() {
    $('#tip .ttip').show();
});

$(document).on('click', '#tip', function() {
    $('#tip .ttip').show();
});

I have tried the following, but they both did not work.

$(document).on('mouseout, click', '#tip', function()
$(document).on({'mouseout', 'click} '#tip', function()
like image 972
Jon Avatar asked Dec 07 '12 21:12

Jon


People also ask

What is on() in jQuery?

The on() method attaches one or more event handlers for the selected elements and child elements. As of jQuery version 1.7, the on() method is the new replacement for the bind(), live() and delegate() methods.

How can use two events in jQuery?

To trigger the same function with multiple events, use the jQuery on() method with multiple events such as click, dblclick, mouse enter, mouse leave, hover, etc.

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

What is difference between on and bind in jQuery?

jQuery bind() Method Use the on() method instead. The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.


1 Answers

You almost had it ..

You need to use a space between the events

$(document).on('mouseout click', '#tip', function() {
    $('#tip .ttip').show();
});

Although, binding to the document is frowned upon. It mimics the .live method which has been deprecated for this reason (and a few others).

Quote

For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.


See the docs at http://api.jquery.com/on/

Quoting

on( events [, selector] [, data], handler(eventObject) )
events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".

like image 64
Gabriele Petrioli Avatar answered Oct 01 '22 11:10

Gabriele Petrioli