Vish
Vish

Reputation: 473

.css function does not work inside of handler function

I want to change css properties inside of a named function thant handles the click event. If I call .css in an anonymous function defined in the click event, it works. However, I want to call .css inside of a named function defined inside the handler function. Here's my code.

$(document).ready(function () {
    $('#popup').click(partial(coolTransition, $(this)));
});

function coolTransition(elem) {
    shrink();

    function shrink() {
        elem.css('background-color', '#000000');
    }
}

//used to implement partial function application so that I can pass a handler reference that takes arguments. 
//see http://stackoverflow.com/questions/321113/how-can-i-pre-set-arguments-in-javascript-function-call-partial-function-applic
function partial(func /*, 0..n args */ ) {
    var args = Array.prototype.slice.call(arguments, 1);
    return function () {
        var allArguments = args.concat(Array.prototype.slice.call(arguments));
        return func.apply(this, allArguments);
    };
}

Thanks in advance for help.

Upvotes: 0

Views: 194

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

In:

$(document).ready(function() {
    $('#popup').click(partial(coolTransition, $(this)));
});

$(this) is $(document). You need $(this) to take on the context of $('#popup'), and for this you need a function:

$(document).ready(function() {
    $('#popup').click((function() {
       return partial(coolTransition, $(this));
    })());
});

Alternatively, you can just avoid $(this) entirely:

$(document).ready(function () {
    var $elm = $('#popup');
    $elm.click(partial(coolTransition, $elm));
});

Really, though, this whole usage of partial seems overly complex. Why do you think that you need it? The easiest approach is:

$(document).ready(function() {
    $('#popup').click(function() {
       coolTransition($(this));
    });
});

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816462

What do you think $(this) refers to in the second line? It is not $('#popup'). If you want to refer to it, you have to create a reference first:

$(document).ready(function () {
    var $popup = $('#popup');
    $popup.click(partial(coolTransition, $popup));
});

That said, using partial is not necessary. You could also do:

$('#popup').click(function() {
    coolTransition($(this));
});

or even

$('#popup').click(function() {
    $(this).css('background-color', '#000000');
});

And there are many other ways...

Btw. defining shrink inside coolTransition seems to be unnecessary. Don't do it unless you have a reason.

Upvotes: 2

Related Questions