JQuery event chain

Based on this question

I don’t want to clog my finished things, expecting a “click event” AND a “change event” AND a “mouse event”. I want to have it all in one function or event.

Is it possible to link events together. I want to capture not only the keyboard, but also a click or change in case the user is not on the keyboard.

<script language="javascript" type="text/javascript"> $(document).ready( function () { setMaxLength(); $("textarea.checkMax").keyup(function(){ checkMaxLength(this.id); } ); $("textarea.checkMax").mouseover(function(){ checkMaxLength(this.id); } ); }); </script> 

It works

 $(document).ready( function () { setMaxLength(); $("textarea.checkMax").bind("click mouseover keyup change", function(){checkMaxLength(this.id); } ) }); 
+6
javascript jquery
source share
2 answers

I think you are looking for a binding. A binding can bind multiple events to the same function using one call instead of using a chain:

 $("textarea.checkMax").bind("keyup mouseover", checkMaxLength); 
+18
source share

Anything that a jQuery object returns can be used to chain. In general, everything returns a jQuery object, so if the API does not explicitly say that it is not, it is possible that a particular method returns a jQuery object and can be bound.

In the case of events, yes, they return a jQuery object and can be chained. Look here

In your case, you can make an external function that takes a single parameter, the object in which the event occurred, and then check its length or whatever you want to do. Then you just call mouseUp(myFunction).mouseOut(myFunction).keyPress(myFunction) or something else that you want to combine together.

Here is a more explicit example:

 <script language="javascript" type="text/javascript"> $(document).ready( function () { setMaxLength(); $("textarea.checkMax").keyup(checkMaxLength()). mouseover(checkMaxLength(this.id)); }); </script> 
+5
source share

All Articles