I wanted to make it so that when you hover on an item in a dropdown menu, all of the items besides the one you hover on change color. To get this effect, I tried to use .not() selector in JQuery but I am unsure how to select the specific child element (which is h1
in this case).
I tried writing .not(this).
as well as .not(children)
... they didn't work. See the JQuery code.
<div>
<h1>Lorem</h1>
<div class="dropdown">
<a href="#">111</a>
<a href="#">222</a>
<a href="#">333</a>
</div>
</div>
<div>
<h1>Ipsum</h1>
<div class="dropdown">
<a href="#">111</a>
<a href="#">222</a>
<a href="#">333</a>
</div>
</div>
<div>
<h1>Dolor</h1>
<div class="dropdown">
<a href="#">111</a>
<a href="#">222</a>
<a href="#">333</a>
</div>
</div>
JQuery:
$(function() {
$('div').mouseenter(
function() {
$(this).find('.dropdown').slideDown(300);
$('h1').css({
'color': '#808080'
});
});
$('div').mouseleave(
function() {
$(this).find('.dropdown').slideUp(300);
$('h1').css({
'color': 'white'
});
});
});
CodePudding user response:
if i understand your problem right, try this:
$(function () {
$('div').mouseenter(
function () {
$(this).find('.dropdown').slideDown(300);
$('h1').not(this).css({ 'color': '#808080' });
$(this).find('h1').css({ 'color': 'white' });
});
$('div').mouseleave(
function () {
$(this).find('.dropdown').slideUp(300);
$('h1').css({ 'color': 'white' });
});
});
CodePudding user response:
Consider the following.
$(function() {
$('div').hover(
function(event) {
var siblings = $("div").not(this);
$('.dropdown', siblings).slideDown(300);
$('h1', siblings).css({
'color': '#808080'
});
},
function() {
var siblings = $("div").not(this);
$('.dropdown', siblings).slideUp(300);
$('h1', siblings).css({
'color': 'white'
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h1>Lorem</h1>
<div class="dropdown">
<a href="#">111</a>
<a href="#">222</a>
<a href="#">333</a>
</div>
</div>
<div>
<h1>Ipsum</h1>
<div class="dropdown">
<a href="#">111</a>
<a href="#">222</a>
<a href="#">333</a>
</div>
</div>
<div>
<h1>Dolor</h1>
<div class="dropdown">
<a href="#">111</a>
<a href="#">222</a>
<a href="#">333</a>
</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
This only works as expected after the first hover
event. We use the same selector and then remove this
from the group. Now the items act as expected.
See More: