-1

Possible Duplicate:
jQuery $(this) vs this

This code in this video Tutorial

in a Very useful blog jquery for designers

$('.navigation').each(function () {
    var $links = $('a',this);
    $links.click(function  () {
        var $link = $(this),
            link = this;
            if ($link.is('.selected')) {
                return;
        }
        $links.removeClass('selected');
        $link.addClass('selected')
    });
});

What is the difference between $(this) and this?

Please explain the simple difference in coding.

Community
  • 1
  • 1
Tarek Saied
  • 6,482
  • 20
  • 67
  • 111

4 Answers4

8

Within the handler being pased into click, this will refer to the DOM element that the click handler was attached to. Calling $() on it ($(this)) wraps that up in a jQuery instance, making various jQuery functions available to you.

In your quoted code, the link = this line is unnecessary as nothing ever uses link. The $link = $(this) line, though, creates a jQuery wrapper around the link so you can use functions like is and addClass.


Off-topic

  1. You probably want to change if ($link.is('.selected')) to if ($link.hasClass('selected')) so that jQuery doesn't have to parse the CSS selector.
  2. You have a typo, the "o" in removeClass is missing.
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

this is native JavaScript that references the current object in scope. $(this) is jQuery wrapped (adding additional properties) to that priormentioned object. Examples:

Plain JS

var person = {
    SayGoodbye: function(){
        this.wave();
        this.exit();
    },
    wave: function(){
        //code to wave
    },
    exit: function(){
        //code to exit
    }
}

person.SayGoodbye();

Some jQuery

//a submit button
$('#myBtn').click(function(){
    $(this).attr('disabled', true);
    $(this).text("Submitting...");
});
pixelbobby
  • 4,368
  • 5
  • 29
  • 49
1
// get everything with the class navigation
$('.navigation').each(function () {
    // get all anchor tags in that context
    var $links = $('a',this);
    // assign a listener for the click event.
    $links.click(function  () {
        // set $link = jQuery wrapper around this
        var $link = $(this),
        // set link = this;
        link = this;
        // if the link has the selected class do nothing
        if ($link.is('.selected')) {
                return;
        }
        //otherwise remove it and then add it again???
        $links.remveClass('selected');
        $link.addClass('selected')
    }); // exit anchor loop
}); // exit nav. loop

P.S. the link variable is unused above.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
0

'this' is the DOM element as accessible by normal JavaScript, whereas when you turn this into $(this), you are creating a JQuery object with more jQuery added API out of that DOM element.

sudipto
  • 2,472
  • 1
  • 17
  • 21