Manju Manju - 6 days ago 5
jQuery Question

How to get the instance of the current parent selector within a inner selector callback function in jquery

I'm trying to scroll the window down by 200px on click of '.sbSelector', If the clicked element (i.e '.sbSelector') is positioned at less than 200px from bottom of window height.

$(document).on('click', '.sbSelector', function(){
var windowHeight = $(window).height();
var drpdwnOffsetTop = parseFloat($(this).offset().top - $(window).scrollTop());
if(parseFloat(windowHeight - drpdwnOffsetTop) < 200){
var temp = $(window).scrollTop() + 200;
$('html, body').animate({scrollTop: temp}, 500, function(){
**// How to get the instance of current '.sbSelector' here**
**// $(this) ll point to $(html,body), where as i need a reference to the current $('.sbSelector')**
});

}
});


My query is how can a get an instance of current '.sbSelector' within the $('html,body').animate function callback. Bcoz there could be many '.sbSelector' elements in the document and i want to point to the current clicked '.sbSelector' within the animate callback.

Answer

Take a look at the JavaScript Scope for more information on global variables.

$(document).on('click', '.sbSelector', function(){
     var windowHeight = $(window).height();
     var drpdwnOffsetTop = parseFloat($(this).offset().top - $(window).scrollTop());
     var that = $(this);
     if(parseFloat(windowHeight - drpdwnOffsetTop) < 200){
         var temp = $(window).scrollTop() + 200;
         $('html, body').animate({scrollTop: temp}, 500, function(){
             console.log(that);
         });
     }
 });

Alternatively, you can bind it to the Browser Object Model:

$(document).on('click', '.sbSelector', function(){
     var windowHeight = $(window).height();
     var drpdwnOffsetTop = parseFloat($(this).offset().top - $(window).scrollTop());
     window.that = $(this);
     if(parseFloat(windowHeight - drpdwnOffsetTop) < 200){
         var temp = $(window).scrollTop() + 200;
         $('html, body').animate({scrollTop: temp}, 500, function(){
             console.log(window.that);
         });
     }
 });

Note: When setting it explicitly on the window object, be careful not to override current properties of the window object. Additionally, this will not work in certain environments like node.js.