Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery event chaining

Based on this question

I don't want to litter my ready stuff waiting for a "click event" AND a "change event" AND a "mouseover event" I want to have all that stuff in a single function or event.

Is is possible to chain the events together. I want to capture not only a keyup, but also a click or a change in case the user isn't 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>

This works

$(document).ready( function () {
    setMaxLength(); 
    $("textarea.checkMax").bind("click mouseover keyup change", function(){checkMaxLength(this.id); } )
});
like image 491
MrChrister Avatar asked Jan 16 '09 20:01

MrChrister


People also ask

What is jQuery chaining?

Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.

Which of the following are the characteristics of chaining in jQuery?

The jQuery provides another robust feature called method chaining that allows us to perform multiple action on the same set of elements, all within a single line of code. This is possible because most of the jQuery methods return a jQuery object that can be further used to call another method.

What is Chainable?

chainable (not comparable) Capable of being chained or connected together.


2 Answers

I think you are looking for bind. Bind can wire multiple events to the same function using a single call instead of using a chain:

$("textarea.checkMax").bind("keyup mouseover", checkMaxLength);
like image 140
OdeToCode Avatar answered Sep 29 '22 04:09

OdeToCode


Anything that returns the jQuery object can be used to chain. In general, everything returns the jQuery object, so if the API doesn't explicitly say it doesn't, chances are that the particular method does return the jQuery object and can be chained.

In the case of events, yes, they do return the jQuery object and can thus be chained. See Here

In your case, you can make an external function that takes one parameter, the object that the event happened on, and then check the length of it, or whatever else you want to do. Then, you just call mouseUp(myFunction).mouseOut(myFunction).keyPress(myFunction) or whatever else you were looking to chain 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>
like image 40
cdeszaq Avatar answered Sep 29 '22 03:09

cdeszaq