Linking multiple events for the same element, and then filtering on specific actions

I am trying to associate a blur and keyup event handler with a text box; I only want the logic to be executed in all blur events and in the case of the keyboard, only when the user presses Enter / return (code 13). It should be simple if I can determine which events were captured, but I cannot find something that describes what I need to look for. A few simple points for a simple answer.

+4
source share
3 answers

You can use the jQuery event object to get event information. 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 this event is blur .

 $('#textBox').bind('blur keyup', function(e){ if( typeof e.which === 'undefined' || e.which === 13 ){ // Code... } }); 
+13
source

Use event.type :

 $('input:text').bind('keyup blur', function(e){ alert(e.type); }); 

JS Fiddle .

 $('input:text').bind('keyup blur', function(e){ var t = e.type; if (t == 'blur'){ $(this).css('background-color','red'); } else if (t== 'keyup') { $(this).css('background-color','green'); } }); 

JS Fiddle demo .

Link:

+2
source
 $('input').keyup(function(e){ var code = (e.keyCode ? e.keyCode : e.which); if(code == 13) /* enter was pressed */ your_function(); }); 
0
source

All Articles