0

I have created a simple functionality using jquery to show and hide a div on hover of an anchor. But, as soon as I leave the anchor tag, the div disappears. I'm unable to go through the div. I should be able to stay on the div element. please can any one help on this.

Here is the fiddle

http://jsfiddle.net/mvqxy9pb/

<style>
.container {
width: 200px;
position: relative;
display: inline-block;
}


.dropdown{
position:absolute;
left:0px;
width:250px;
top:18px;
background-color:#c03;
height:100px;
display:none;
}

</style>


<script>
$(document).ready(function(){
$(".menuItem").hover(function(){
$(".dropdown").show();
}, function(){
$(".dropdown").hide();
});
});
</script>


<div class="container">


<div class="wrap">

<a href="#" class="menuItem">Menu Item</a>

<div class="dropdown">
asasasasa
</div>

</div>


</div> 

3 Answers 3

4

Change the below line

$(".menuItem").hover(function(){

to this

$(".menuItem, .dropdown").hover(function(){

Demo: http://jsfiddle.net/mvqxy9pb/1/

3
  • what if the div and the anchor tag has distances between them. Yours just working fine because the anchor tag and the div is nearer to each other but what if div is somewhere else then your code won't work .Try giving margin-top:5% to .dropdown Commented Feb 18, 2015 at 6:40
  • Why do you need a space between menu and its sub-menu(dropdown)?
    – SO-user
    Commented Feb 18, 2015 at 6:47
  • Why not ? who told you that it should be directly under the anchor tag ? Did OP mention ? Commented Feb 19, 2015 at 7:36
1

You can try also using css instead of jquery

http://jsfiddle.net/mvqxy9pb/3/

I've added menuItem as primary div to (anchor and dropdown)

<div class="menuItem">
   <a href="#">Menu Item</a>
   <div class="dropdown">
       asasasasa
   </div>
</div>

And i've removed the position:relative; from container and added to menuItem then added on menuItem:hover added display:block; for showing the dropdown.

.menuItem:hover .dropdown {
    display:block !important;
}
0

Try

$(document).ready(function(){
  $(".menuItem, .dropdown").hover(function(){
   $(".dropdown").show();
  }, function(){
   $(".dropdown").hide();
  });
});

https://jsfiddle.net/mvqxy9pb/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.