jquery - Affect different element in parent div on hover -
when hover on <h3>
within <div>
, expands <ul>
elements in <div>
elements class.
i'm bit confused on how affect only <ul>
within <div>
hovering on <h3>
?
i have html structured this:
jquery(document).ready(function() { jquery("div.sidemenugroup h3").hover(function() { jquery("div.sidemenugroup ul").slidedown() }, function() { jquery("div.sidemenugroup ul").slideup(); }); });
div.sidemenugroup ul { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="sidemenugroup"> <h3>some text</h3> <ul> <li>list item 1</li> <li>list item 2</div> </ul> </div> <div class="sidemenugroup"> <h3>some other text</h3> <ul> <li2nd>list item 1</li> <li>2nd list item 2</div> </ul> </div>
identify element "hover" event fired using javascript's "this" keyword.
"when function used event handler,
this
set element event fired from"
once have identified element fired "hover" (<h3>
), can traverse element corresponding <ul>
. way code structured, <ul>
elements follow <h3>
elements. so, suggest using jquery's next()
, so:
jquery(this).next();
that select next element after "hovered" <h3>
, <ul>
. can slide element or down.
jquery(document).ready(function() { jquery("div.sidemenugroup h3").hover(function() { jquery(this).next().slidedown() }, function() { jquery(this).next().slideup(); }); });
div.sidemenugroup ul { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="sidemenugroup"> <h3>some text</h3> <ul> <li>list item 1</li> <li>list item 2</li> </ul> </div> <div class="sidemenugroup"> <h3>some other text</h3> <ul> <li>list item 1</li> <li>2nd list item 2</li> </ul> </div>
refinement
you can simplify code bit making use of jquery's slidetoggle()
. note hover()
accept single function. so, can trigger same slide animation when mouse enters or leaves element. use toggle slide state.
the .hover() method, when passed single function, execute handler both mouseenter , mouseleave events.
also, prevent animations building in queue, recommend adding stop()
before slide.
see these refinements demonstrated below:
jquery(document).ready(function() { jquery("div.sidemenugroup h3").hover(function() { jquery(this).next().stop(true, false).slidetoggle(); }); });
div.sidemenugroup ul { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="sidemenugroup"> <h3>some text</h3> <ul> <li>list item 1</li> <li>list item 2</li> </ul> </div> <div class="sidemenugroup"> <h3>some other text</h3> <ul> <li>list item 1</li> <li>2nd list item 2</li> </ul> </div>
Comments
Post a Comment