I believe that 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 hover
event was currently captured. The e
parameter is actually an object, containing various event information applied.
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><divclass="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>
Update
Since the context of the anonymous function used by setTimeout
is not bound to the jQuery element, it needs to be referenced within 'setTimeout.'
@Sergio explained in his answer how to solve this problem by setting a variable referencing the jQuery selector and using it within setTimeout
. But, if you prefer, jQuery offers a solution through a function called $.proxy
.
Here's what the code looks like:
$ (document) .ready (function () {
$ ('. image') hover (function (e) {
$(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);
});
});
$.proxy
is intended to bind a context to the function. That is, you define through it "who" will be the this
used by the 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>