Reputation: 972
I try to write a small jquery plugin. In the past i used javascript mainly. I don`t understand the this.each function. First of all i write a new method for $.fn. In this method i want to get the offset().top of all elements.
$.fn.jquerynParalFade = function() {
this.each(function() {
console.log($(this).offset().top);
});
}
This works fine for me. But if i resize the screen (for example on turning my device) i want to get the new position of all elements. For this i added a function which could run on resize.
$(window).resize(function() {
resize();
});
Now I have the problem that i can´t use this.each() inside of the function. Instead I use $(this).each
. But if i do the console tells me that offset()
isn't a function of $(this)
.
This is what that code looks like:
function resize(){
$(this).each(function(index) {
console.log($(this).offset().top);
});
}
So how i use this.each in a function of a jquery plugin?
Upvotes: 0
Views: 56
Reputation: 1524
You will have to bind the context of what this
is to your function for the resize to work properly:
var myResize = resize.bind(this)
myResize() // now it should work
Another way is to pass the context:
function resize (context) {
context.each( ... )
}
$(window).resize(function () { resize(this) })
Some concepts to read about:
Upvotes: 1