Sam D20
Sam D20

Reputation: 2575

How to fade in a div on hover/mouseover using jquery?

I have a div that is set to display:hidden. I want this div to be set to display:block when a certain element (#navbar li a) is hovered over. Here is my javascript.

$('document').ready(function(){
    $("#navbar li a").onmouseover(function{
        $("#navbar ul").css("display","block"); 
    }); 
}); 

I know that $("#navbar li a") is targeting the proper element, as I have tested this. Is there anything wrong with my javascript code?

edit: this is a dropdown menu. #navbar ul is a nested list.

Upvotes: 6

Views: 38843

Answers (5)

Kevin Lynch
Kevin Lynch

Reputation: 24703

Use .hover

$('document').ready(function(){
    $("#navbar li a").hover(function(){
        $("#navbar ul").css("display","block"); 
    }); 
}); 

If you would like a fade in effect then just use .fadeIn

DEMO

$(function() {
$('#div1').hover(function() { 
    $('#div2').fadeIn(); 
}, function() { 
    $('#div2').fadeOut(); 
});
});

For completeness here's a CSS only method:

(FYI this using this method won't fade it as per say, just make it appear on hover and then disappear when not on hover.)

DEMO

#div2 {
    width: 200px;
    height: 200px;
    background: red;
    display: none;
}

#div1:hover ~ #div2 {
    display: block;    
}

Upvotes: 9

North Gork
North Gork

Reputation: 57

If you want the div to actually fade from opaque to 100% then you have start with opaque at say 80% (shown as 0.8) then fade to 100% (shown as 1.0). Since you want to start with a level of opacity the div needs to be hidden using "display none", the opaque level can then be set without the effect being seen, then make it visible and fade to 100%:

 $("div.mydivclass").on("mouseenter", function () {
    $(this).css("display", "none");
    $(this).fadeTo("fast", 0.8);
    $(this).css("display", "");
    $(this).fadeTo("10", 1.0);
});

Upvotes: 2

adeneo
adeneo

Reputation: 318182

Yes, there is something wrong with your code, jQuery doesn't have a onmouseover event, and what you're probably looking for is the mouseenter event, as mouseover fires continously on mousemove:

$(document).ready(function(){
    $("#navbar li a").on('mouseenter', function(){
        $("#navbar ul").show();
    }); 
}); 

on the other hand, you could probably do this with just CSS ?

Upvotes: 2

zod
zod

Reputation: 12417

all the answers are show / hide . your code too. Question is about fade in.

use .fadeIn() .fadeOut instead show hide

http://api.jquery.com/fadeIn/

Upvotes: 2

drip
drip

Reputation: 12943

There is no "onmouseover"

The right syntaxsis is:

$("#navbar li a").on("mouseover", function(){
    $("#navbar ul").show() //Can use just show here
})

Upvotes: 3

Related Questions