David  Hamilton
David Hamilton

Reputation:

Jquery mouse-over fade-in/out (best practices)

I've got working Jquery code to fade in/out descriptive text in a div below the question. The problem? The solution is not very elegant. Here's what I've got:

$("#home").mouseover(function() {
    $("#homeText").fadeIn("slow");
});
$("#homeText").mouseout(function() {
    $("#homeText").fadeOut();
});

I know there is better way to do this, I'm just not sure what it is.

Upvotes: 8

Views: 39055

Answers (4)

Luz
Luz

Reputation: 21

$(function () {
    $('#home').hover(function() {
       $('#homeText').fadeIn("slow");
    });
    $('#home').mouseout(function() {
       $('#homeText').fadeOut("slow");
    });
});

Upvotes: 2

fseminario
fseminario

Reputation: 809

How about 3 lines?

<script>

    $(function () {

        $('#home').hover(function() {
           $('#homeText').fadeToggle("slow");
        });

    });


    </script>

Elegant enough?

Upvotes: 7

David  Hamilton
David Hamilton

Reputation:

Jon, Great advice! I used as a staring point though for a more complete solution. Doing this with just the basic hover would still leave me with a hover call for single menu item..A lot of redundant code. So using what you suggested, I came up with this:

$('.topMenu').hover(function()
        {
        $('#_'+this.id).fadeIn("slow");
        },
        function ()
            {
        $('#_'+this.id).fadeOut();      
            });
});

All menu items are given the topMenu class and ID. The corresponding div to display is the same id as the menu item, just prefixed with _ Example: ....

Stuff about us!

...

Thanks!

Upvotes: 2

Jon Erickson
Jon Erickson

Reputation: 115016

you could use hover, the first function will act on a "hover over" and the second will act on a "hover out"

The documentation is located here: http://docs.jquery.com/Events/hover

$("#home").hover(function(){
    $("#homeText").fadeIn("slow");
},
function(){
    $("#homeText").fadeOut();
});

Upvotes: 22

Related Questions