Link to fiddle
I am trying to use $(this) keyword & jquery's hover() function.
There are 3 divs with class 'item', each div contains two child divs, 'trigger' & 'trigger-box', what I am trying to achieve is when user hovers on each 'trigger' div, 'visible' class needs to be added to it's respective 'trigger-box'.
HTML Code:
<div class="container">
<div class="item">
<div class="tirgger">
<h5>Trigger 1</h5>
</div>
<div class="trigger-box">
<h3>trigger box 1</h3>
</div>
</div>
<div class="item">
<div class="tirgger">
<h5>Trigger 2</h5>
</div>
<div class="trigger-box">
<h3>trigger box 2</h3>
</div>
</div>
<div class="item">
<div class="tirgger">
<h5>Trigger 3</h5>
</div>
<div class="trigger-box">
<h3>trigger box 3</h3>
</div>
</div>
JavaScript Code:
$('.item').hover(function() {
console.log("hover in");
$('.item .trigger-box', this).addClass('visible');
}, function() {
console.log("hover out");
$('.item .trigger-box', this).removeClass('visible');;
});
I've tried with multiple combinations '$(this)' keyword but couldn't get it to work, any help would be appreciated.
Get rid of the .item part of
$('.item .trigger-box', this);
That syntax is the exact same process as
$(this).find('.item .trigger-box')
But since this is the .item it will not find that selector. It's looking for itself inside itself
Working version
You can try this:
$('.tirgger').hover(function() {
$(this).parent().find('.trigger-box').addClass('visible');
}, function() {
$(this).parent().find('.trigger-box').removeClass('visible');;
});
.visible {
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item">
<div class="tirgger">
<h5>Trigger 1</h5>
</div>
<div class="trigger-box">
<h3>trigger box 1</h3>
</div>
</div>
<div class="item">
<div class="tirgger">
<h5>Trigger 2</h5>
</div>
<div class="trigger-box">
<h3>trigger box 2</h3>
</div>
</div>
<div class="item">
<div class="tirgger">
<h5>Trigger 3</h5>
</div>
<div class="trigger-box">
<h3>trigger box 3</h3>
</div>
</div>
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