Somenath Sinha
Somenath Sinha

Reputation: 1214

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.

Upvotes: 3

Views: 162

Answers (3)

Liam
Liam

Reputation: 29664

$(this) is just an object like any other. Simply pass it into your function:

counter(hCount, $(this));
....

function counter(count, thisFromPreviousFunction)

Upvotes: 3

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

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

Upvotes: 6

Gregoire
Gregoire

Reputation: 767

Uncaught TypeError: Cannot read property 'defaultView' of undefined

This comes from the line var pPos = $(this).css('left');

as $(this) isn't defined in your function (the function isn't related to a Selector, so $(this) doesn't exists as you think).

$(document).ready(function(){

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

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

  function counter(count, selector) {
      count++;
      if(count === 10)  {
          count = 0;
          pPos = 0;
      }
      else {
          var pPos = selector.css('left'); // Use the given selector
          pPos = pPos.substring(0,(pPos.length-2))
          pPos -= 367;
      }
      return pPos;
  }
});

https://jsfiddle.net/yw2b4tyt/

Upvotes: 3

Related Questions