March 9, 2013

$(this).attr not working

Question by user1716672

I’m using fancybox and I want to get the element class before fancybox executes. So I have:

$(".agent-file-popup").fancybox({
    'onStart': function () {
        console.log($(this).attr('class'));
        console.log($(".agent-file-popup").attr('class'));
        return true;
    }
});

The first log outputs “undefined” but the second log outputs the correct class. Why can I not use “this” as the element in this situation?

Answer by Starx

$(this) is one of very popular construct to indicate current element is focus, which can be used inside event and selector functions. This is as equal to JavaScript’s this construct wrapped by jQuery’s function to provide access to jQuery’s function.

$(".user").click(function() {
    //Here $(this) will represent the element that was click with class .user
});

Plugins are generally developed as extensions to jQuery’s jQuery() function, they are hardly responsible to detect the current element.

So, when you are initializing the plugin $(this) might easily represent nothing.

Fancybox has a way to get the current element.

onstart: function(itemArray, selectedIndex, selectedOpts){
 // selectedIndex holds the current selected box on itemArray as the collection object.
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!