I’m building a plugin with the code below. If I change $(opts.section, this).animate to $(opts.section).animate it works as I want it too, but it animates all instances of the section element, and I want it to only affect this current one. Once I add “this” to it, it stops working all together.
$('.next', this).on({
click: function() {
if(count+2 <= totalElems) {
count += 1;
currentAnimationSpot += singleElem + opts.offset;
$(opts.section, this).animate({
left: -currentAnimationSpot
});
}
}
});
$('.prev', this).on({
click: function(){
if(count != 1) {
count-=1;
currentAnimationSpot -= singleElem + opts.offset;
$(opts.section, this).animate({
left: -currentAnimationSpot
});
}
}
});
The
thisinside the function is different than thethisoutside your function. EDIT: as @FabricioMatte’s answer says -”thisin the scope of your $(“.next”, this) handler references the element that triggered the handler”.So, you need to store the outer
thisin a separate variable so you can access it inside your function. E.g.Even though this might seem strange at first, it’s actually the same behavior you’d see any time you assign a new value in the local scope of a function, it’s just that the
thisassignment is hidden.Quick example of closures/scoping: Say you have a variable
scoped, you could replicate the behavior as follows:Just imagine you replaced “scoped” with “this” and you should get the general idea (it’s as if someone set
var this = triggerElementinside the scope of the function.