Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding multiple events for the same element, then filtering specific actions

Tags:

jquery

I am trying to bind a blur and keyup event handler to a textbox; I only want the logic to execute on all blur events and in the event of the keyup, only upon the user hitting Enter/ return (code 13). This should be simple if I can tell which of the events were captured, but I can't seem to find something that describes what I need to look for. Quick few points for a simple answer.

like image 672
Jeremy Holovacs Avatar asked Aug 23 '11 15:08

Jeremy Holovacs


People also ask

Which of the event attach an event handler function for one or more events to the selected elements?

on() Attach an event handler function for one or more events to the selected elements.

Can we pass two events in addEventListener?

Unfortunately, you can't pass in multiple events to a single listener like you might in jQuery and other frameworks. For example, you cannot do this: document. addEventListener('click mouseover', function (event) { // do something... }, false);

What is bind event explain with example?

The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs. event: This is an event type which is passed to the selected elements. data: This is the data which can be shown over the selected elements.

Can we use addEventListener to bind multiple listeners to a node in Dom?

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. i.e the window object.


1 Answers

You can use the jQuery event object to get info about the event. event.type will tell you which event was triggered.

$('#textBox').bind('blur keyup', function(e){
   if( e.type === 'blur' || (e.type === 'keyup' && e.which === 13) ){
     // Code...
   }
});

You can also just check event.which which will be undefined when it's a blur event.

$('#textBox').bind('blur keyup', function(e){
   if( typeof e.which === 'undefined' || e.which === 13 ){
     // Code...
   }
});
like image 120
Rocket Hazmat Avatar answered Nov 15 '22 21:11

Rocket Hazmat