Jon
Jon

Reputation: 8511

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()

Upvotes: 5

Views: 6074

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

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".

Upvotes: 6

Dave G
Dave G

Reputation: 9767

According to jQuery API, 'events' is space separated

.on( events [, selector] [, data], handler(eventObject) )

events: One or more space-separated event types and optional namespaces, such as click or keydown.myPlugin.

selectorA: Selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

data: Data to be passed to the handler in event. Data when an event is triggered.

handler(eventObject): A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.

Upvotes: 2

hajpoj
hajpoj

Reputation: 13379

I believe you can jus space sparate them like so

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

Upvotes: 1

Related Questions