Sure, you can do this, but it's less complicated than that.

Don't make your function a method of the jQuery object. Simply make it an
ordinary named function with *exactly* the same code as the anonymous
function.

So your code:

    $("#test").click(function(){ $(this).css("color","pink") });

becomes:

    $("#test").click(update_div);
    function update_div(){ $(this).css("color","pink") }

The only caveat would be that if you move this named function to a different
location, it may lose access to variables declared in the outer function.

Suppose your code looked like this:


    function test() {
        var color = 'pink';
        $("#test").click(function(){ $(this).css("color",color) });
    }

This would work the same:

    function test() {
        var color = 'pink';
        $("#test").click(setColor);
        function setColor(){ $(this).css("color",color) }
    }

But this would not work:

    function test() {
        var color = 'pink';
        $("#test").click(setColor);
    }

    function setColor(){ $(this).css("color",color) }

because setColor has lost its access to the variable.

-Mike

> -----Original Message-----
> From: jquery-en@googlegroups.com 
> [mailto:[EMAIL PROTECTED] On Behalf Of DAZ
> Sent: Saturday, December 06, 2008 10:55 AM
> To: jQuery (English)
> Subject: [jQuery] Separate Functions for Events
> 
> 
> Hi, I've just started using jQuery and have run into the 
> following problem that I'm sure has an easy answer.
> 
> I want a function to run after an event, for example, if I 
> click on a test div:
> 
>  $("#test").click(function(){ $(this).css("color","pink") });
> 
> Instead of this, I want to have the effects of the click in a 
> separate function, like this:
> 
> $("#test").click(update_div)
> 
> jQuery.fn.update_div = function() {
> this.css("color","pink");
> };
> 
> I know the example is longer, but if I wanted to do more 
> complex stuff, I feel it would be better put in a separate function.
> 
> Is this possible?
> 
> thanks,
> 
> DAZ
> 

Reply via email to