Search code examples
jqueryscopeinteraction

Confused by jQuery 'parent' scope on event trigger


When a user clicks on a link, I'm trying to check if that link's container has a class of active assigned to it.

But I think I'm having a problem with scoping, as while the visual style is applied by the browser, the click isn't seeing that class assignment when it's triggered.

I've created a jsfiddle replicating the problem. Enlightenment much appreciated.


Solution

  • $link is out of scope for the annoynmous function inside your handler. You need to use $(this) inside the click handler instead:

    $links.each( function(i) {
        $link = $(this);
        $link.click( function(e) {
            e.preventDefault();
            console.log('L' + i + ': ' + $(this).parent().hasClass('active'));
        });
    });
    

    See the updated jsFiddle.


    You can also use event data to act as closures if you have to solve this without using $(this), for example:

    $links.each( function(i) {
        $link = $(this);
        $link.click({ link : $link }, function(e) {
            e.preventDefault();
            //console.log('L' + i + ': ' + $(this).parent().hasClass('active'));
            e.data.link.parent();
        });
    });