Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a single event handler to multiple events with jQuery

Tags:

jquery

events

I have the following div with different functions for onblur, onmousedown, onmouseup, and onfocus.. I want to minimize the code and have only one function call inside div for all the function states. I want to do this with jquery So in other words. I want to create a function called functionAll and put all of function1 to function 4 with it's mouse state inside, then just use functionAll inside the Div. How can I do something like this?

<div contentEditable="true"
     onblur="function1();"
     onmousedown="return function2(event);"
     onmouseup="function3();"
     onfocus="function4();">
    test test
</div>
like image 552
Hussein Avatar asked Jan 17 '11 05:01

Hussein


People also ask

Can you add multiple events to .on jQuery?

The . on() method provides several useful features: Bind any event triggered on the selected elements to an event handler. Bind multiple events to one event handler.

Can you have multiple event listeners for the same event?

The addEventListener() methodYou can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.


1 Answers

You should put an id on the div, say "test", then:

$('#test').bind('blur mousedown mouseup focus', function (e) {
    // This is your combined function
    // Inside here you can use e.type to find out whether it was a
    // "blur", "mousedown", "mouseup", etc...
});

The HTML will look like:

<div id="test" contentEditable="true">
    test test
</div>
like image 138
David Tang Avatar answered Sep 29 '22 15:09

David Tang