Possible Duplicate:
jquery passing $(this) to other functions
I am writing a Javascript/jQuery function (NOT REFACTORED YET) but I am getting an error from using $(this). It’s a little difficult to explain so I’ll add the code and hopefully it will become more clear:
var accordion = 'div.accordionContent';
var accordButton = 'div.accordionButton';
var accordClosedArrow = 'url(/public/img/accordion-closed-arrow-';
var accordOpenArrow = 'url(/public/img/accordion-open-arrow-';
$(accordion).hide();
var accordFunc = function(arrowColor){
var img;
if ($(this).next(accordion).is(':visible')) {
img = accordClosedArrow + arrowColor + '.png)';
}
else {
img = accordOpenArrow + arrowColor + '.png)';
}
// these lines throw errors because of $(this)
$(this).css({backgroundImage:img}).next().slideToggle('slow').siblings(accordion)
.slideUp();
$(this).siblings()
.css({backgroundImage:accordClosedArrow + arrowColor + '.png)' + 'no-repeat'});
};
$(accordButton).live('click',function(){
accordFunc('blue');
});
$(accordButton + 'B').live('click',function(){
accordFunc('orange');
});
Not sure why passing $(this) causes the Chrome console to throw an error:
Uncaught TypeError: Cannot read property ‘firstChild’ of undefined
Replace
accordFunc('blue');withaccordFunc.call(this, 'blue');and do likewise for the other call to that function.The
thisvalue is not preserved when you call another function so insideaccordFuncit points to the window object or null (if strict mode is active). Another option would be passingthisas a normal argument and changing the function definition e.g. tofunction accordFunc(elem, arrowColor)and useeleminstead ofthisinside that function.