user2167264
user2167264

Reputation: 23

jquery mouseenter and fadeTo

I want a div to be faded to opacity 1 when mouse enters, and to 0.5 when it leaves. This is my code:

        <script>
    $(document).ready(function(){
        $("#header").mouseenter(function(){
        $("#header").fadeTo('fast', 1);
        });
        $("#header").mouseleave(function(){
            $("#header").fadeTo('fast', 0.5);
    });

    }


    </script>

HTML:

<body>

        <div id="header">
            <h1>Hello!</h1>
            <p>blah blah...</p>
        </div>

</body>

I have a div in the body containing one h1 and one p. Nothing happens when I move the mouse over it. Is something wrong?

Upvotes: 0

Views: 401

Answers (2)

elclanrs
elclanrs

Reputation: 94121

How about css?

#header {
  opacity: .5;
  transition: opacity .3s ease-in-out;
}
#header:hover {
  opacity: 1;
}

Just make sure to add all the css vendor prefixes. This is better than using jQuery IMO. If browser doesn't support transition or opacity it's no big deal, that's what "graceful degradation" is all about.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382274

Your wrong indentation hides a syntax error :

$(document).ready(function(){
    $("#header").mouseenter(function(){
        $("#header").fadeTo('fast', 1);
    });
    $("#header").mouseleave(function(){
        $("#header").fadeTo('fast', 0.5);
    });
}); // <= missing parenthesis

Other than that, it works. Be careful that 0.5 isn't really transparent for all color combinations.

Upvotes: 1

Related Questions