I think instead of using:
$(e).children('.button').addClass('animated zoomIn');
You should use:
$(this).children('.button').addClass('animated zoomIn');
The this
in this case refers to the element in which the event was currently captured hover
. The parameter e
is actually an object, containing various information of the applied event.
See my example working:
$(function () {
$('.image').hover(function () {
$(this).children('.button')
.addClass('red');
}, function () {
$(this).children('.button')
.removeClass('red');
});
});
.image{
height:100px;
width: 100px;
background-size: 100% auto;
background-repeat: no-repeat;
}
.red{
background-color: #800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="image" style="background-image: url(https://placeholdit.imgix.net/~text?txtsize=33&txt=Imagem%20de%20Teste&w=150&h=150);">
<button class="button">Hello</button>
</div>
<div class="image" style="background-image: url(https://placeholdit.imgix.net/~text?txtsize=33&txt=Imagem%20de%20Teste&w=150&h=150);">
<button class="button">Hello</button>
</div>
<div class="image" style="background-image: url(https://placeholdit.imgix.net/~text?txtsize=33&txt=Imagem%20de%20Teste&w=150&h=150);">
<button class="button">Hello</button>
</div>
Updating
As the context of the anonymous function used by setTimeout
is not bound to the jQuery element, it is necessary to reference it within `setTimeout.
@Sergio explained in his reply how to solve this problem by defining a variable referencing the jQuery selector and using it within setTimeout
. But if you prefer, jQuery offers a solution through a function called $.proxy
.
See what the code would look like:
$(Document). ready(Function() {
$('. image'). Hover(Function(and) {
$(this).children('.button').addClass('animated zoomIn').css("opacity", "1");
setTimeout($.proxy(function() {
$(this).removeClass('animated zoomIn');
}, this), 1000);
}, function(e) {
$(this).children('.button').addClass('animated zoomOut');
setTimeout($.proxy(function() {
$children.removeClass('animated zoomOut').css("opacity", "0");
}, this), 300);
});
});
The $.proxy
is intended to apply link a context to the function. That is, you define through it "who" will be the this
used by function.
Example:
$(function ()
{
setTimeout($.proxy(function () {
alert(this.name);
}, {name: "Wallace"}), 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
However, another problem has arisen. O remove.Class(...) does not work. <pre> setTimeout(Function() { $(this).Children('.button').removeClass('Animated zoomIn'); }, 300); </pre>
– M_b_85
I mentioned this problem of
this
within thesetTimeout
in my reply.– Sergio
You’re right, I didn’t notice it and it’s already solved. Thank you
– M_b_85