First of all I'm sorry but I'm a really big beginner.
I dont really understand the "this" in the jquery plugin, was looking a lot but couldn't really find any answer.
here is my plugin (im making this only for practice)
jQuery.fn.hoverPlugin = function(){
var element = this;
$(element).animate({"opacity" : ".5"});
$(element).hover(function(){
$(element).stop().animate({"opacity" : "1"});
}, function() {
$(element).stop().animate({"opacity" : ".5"});
});
};
the call
$("img").hoverPlugin();
My problem is this way it adds the animate effect on all images. It's okay if animates on all images on the page load, but when I place the mouse over an image, it animates all.
If I write it in the simple way
$("img").animate({"opacity" : ".5"});
$("img").hover(function(){
$(this).stop().animate({"opacity" : "1"});
}, function() {
$(this).stop().animate({"opacity" : ".5"});
});
It works the way I want.
So if a more experienced developer could explain to me how can I make this in my plugin? I would be really happy.
Thank you
That's because this in the .hoverPlugin function is referencing the $('img') used to call it:
jQuery.fn.hoverPlugin = function(){
var element = this;
$(element).animate({"opacity" : ".5"});
$(element).hover(function(){
$(element).stop().animate({"opacity" : "1"});
}, function() {
$(element).stop().animate({"opacity" : ".5"});
});
};
$(document).ready(function(){
$("img").hoverPlugin();
});
http://jsfiddle.net/ww7gg/
If you try that with console open, you'll see what I mean.
If you just change to this:
$(element).hover(function(){
$(this).stop().animate({"opacity" : "1"});
}, function() {
$(this).stop().animate({"opacity" : ".5"});
});
http://jsfiddle.net/ww7gg/1/
It works.
And this is better:
jQuery.fn.hoverPlugin = function(){
this
.animate({"opacity" : ".5"})
.hover(function(){
$(this).stop().animate({"opacity" : "1"});
}, function() {
$(this).stop().animate({"opacity" : ".5"});
});
};
You don't need element, just use this and chain.
http://jsfiddle.net/ww7gg/2/
On your plugin:
var element = this; is a jquery Collection of element(s):
jQuery.fn.hoverPlugin = function(){
var collection = this.animate({"opacity" : ".5"}); //Fade all elements to .5 opactiy.
collection.each(function() {
var element = this; // Single element from the collection
$el = $(element); //Create 1 jquery object and re-use it on the events.
$el
.hover(function(){
$el.stop().animate({"opacity" : "1"});
}, function() {
$el.stop().animate({"opacity" : ".5"});
});
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With