Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery multiple events to trigger the same function

Is there a way to have keyup, keypress, blur, and change events call the same function in one line or do I have to do them separately?

The problem I have is that I need to validate some data with a db lookup and would like to make sure validation is not missed in any case, whether it is typed or pasted into the box.

like image 360
shaneburgess Avatar asked Mar 28 '10 18:03

shaneburgess


People also ask

Can you have multiple event listeners of the same type?

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

What is event binding in jQuery?

The jQuery bind() event is used to attach one or more event handlers for selected elements from a set of elements. It specifies a function to run when the event occurs. It is generally used together with other events of jQuery. Syntax: $(selector).


2 Answers

You can use .on() to bind a function to multiple events:

$('#element').on('keyup keypress blur change', function(e) {     // e.type is the type of event fired }); 

Or just pass the function as the parameter to normal event functions:

var myFunction = function() {    ... }  $('#element')     .keyup(myFunction)     .keypress(myFunction)     .blur(myFunction)     .change(myFunction) 
like image 75
Tatu Ulmanen Avatar answered Sep 19 '22 15:09

Tatu Ulmanen


As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements.

$(document).on('mouseover mouseout',".brand", function () {   $(".star").toggleClass("hovered"); }) 
like image 40
lesyk Avatar answered Sep 20 '22 15:09

lesyk