Somenath Sinha Somenath Sinha - 4 months ago 7
jQuery Question

How do I pass $(this) to a function?

My code is :

$(document).ready(function(){

var hCount = 0,
eCount = 0,
nCount = 0,
mCount = 0;

$("#head").click(function() {
var pPos = counter(hCount);
$(this).animate({left:pPos+"px"}, 1000);
});

function counter(count)
{
count++;
if(count === 10)
{
count = 0;
pPos = 0;
}
else
{
var pPos = $(this).css('left');
pPos = pPos.substring(0,(pPos.length-2))
pPos -= 367;

}

return pPos;
}


I get an error stating


Uncaught TypeError: Cannot read property 'defaultView' of undefined


I have no idea what's causing this error.

Also, how can I pass the function
counter()
the value of
$(this)
in
$("#head").click
? I can't directly mention
$("#head")
because I'll repeat this functionality with more divs, other than
#head
, while reusing the code in the function counter.

Answer

Just extend counter function with elem argument and pass it within click handling:

function counter(count, elem){
   // ...
}

$("#head").click(function() {
    var elem = $(this);
    var pPos = counter(hCount, elem);
    elem.animate({left:pPos+"px"}, 1000);
});