I'm trying to develop my first jQuery plugin. Basically it appends classes to various elements on site an then changes it when user scrolls (I'm calculating offsets and whatnot). And I think I've hit a wall with this one.
Here's how I start the plugin:
$("div").myPlugin();
And the source:
$.fn.myPlugin = function() {
return this.each(function() {
$(this).addClass("something-" + i);
i++;
});
};
Could someone explain please how to use $(window).scroll in my plugin?
Because once it into "return this.each" it gets attached as many times as many elements there are in this loop...
$.fn.myPlugin = function() {
return this.each(function() {
$(this).addClass("something-" + i);
i++;
$(window).scroll( function() { <!-- here it not only attaches itself x-times but i is always the same -->
...
$(".something-" + i).addClass("active");
...
});
});
};
Putting it after return doesn't do nothing:
$.fn.myPlugin = function() {
return this.each(function() {
$(this).addClass("something-" + i);
i++;
});
$(window).scroll( function() { <!-- doesn't seem to work -->
...
$(".something-" + i).addClass("active");
...
});
};
And before there are no "i"s, also I don't know if I can put anything outside of the "return" scope inside a function (doesn't seem valid to me?):
$.fn.myPlugin = function() {
$(window).scroll( function() { <!-- there is no "i" yet -->
...
$(".something-" + i).addClass("active");
...
});
return this.each(function() {
$(this).addClass("something-" + i);
i++;
});
};
I'm new to jQuery and I'm not sure if I understand the documentation correctly, I was wondering wether it might be better to do not use return here at all? Note this plugin can work with 1 element but usually there will be more divs than 1.
Thanks a lot.