views:

3290

answers:

2

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); } )
});
+4  A: 

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>
cdeszaq
But I am waiting those events to happen. I will clarify my question
MrChrister
Yes, since those functions bind event handlers, and then return the jQuery object, you can chain event bindings just fine.
cdeszaq
Read the documentation available at jQuery.com. It explicitly states that these methods return the jQuery object.
Jonathan Sampson
Sorry if I am being dense, or maybe I don't understand the vocaburlary. An example would be nice.
MrChrister
I wanted this I guess: $("textarea.checkMax").bind("click mouseover keyup", function(e){checkMaxLength(this.id); } )
MrChrister
+3  A: 

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);
OdeToCode