Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify $(this) in jQuery

Whats the best way to find out what $(this) currently equals in jQuery?

For example alert(this); isn't much help.

The reason I ask is that a piece of code is not currently doing what it should do after I have moved the code into a function.

The excerpt below is now in a function, and $(this) now seems to refer to the DOMWindow.

if($(this).hasClass('open'))
  {
    alert('I should be closed');
    $(this).removeClass('open').addClass('closed');
    $(this).parents('article').css('border', '1px solid red').animate({'width': '212px'}, 100, "linear", function() {
    run_masonry();
    });
  }
  else
  {
    alert('I should be open');
    $(this).removeClass('closed').addClass('open');
    $(this).parents('article').css('border', '1px solid blue').animate({'width': '646px'}, 100, "linear", function() {
    run_masonry();
  });
}

How do I keep it as $(this) being the original clicked element?

like image 906
Craig Ward Avatar asked Jan 06 '12 10:01

Craig Ward


2 Answers

Whats the best way to find out what $(this) currently equals in jQuery?

By logging it to the console of your favorite javascript debugging tool (like FireBug or Chrome developer toolbar for example):

console.log($(this));

which will return a jQuery wrapped object. If you want to know more about the native object you could use:

console.log(this);

If you are doing javascript development you should use a javascript debugging tool. alert is not such tool.


Now that you have updated your question with some code source it seems that you are using $(this) in the global scope. Then it will refer to the window object. If you want it to refer to some clicked element or something you will have to first subscribe to the .click event:

$('.someSelector').click(function() {
    // here $(this) will refer to the original element that was clicked.
});

or if you wanted to externalize this code in a separate function:

function foo() {
    // here $(this) will refer to the original element that was clicked.
}

$('.someSelector').click(foo);

or:

function foo(element) {
    // here $(element) will refer to the original element that was clicked.
}

$('.someSelector').click(function() {
    foo(this);
});
like image 116
Darin Dimitrov Avatar answered Oct 26 '22 07:10

Darin Dimitrov


With moving code into a function usually the scope of the code changes. So "this" will no longer refer to the original object but rather to a new one (or the global "window" object). If you show us your code we will be able to identify the problem.

like image 21
devnull69 Avatar answered Oct 26 '22 08:10

devnull69