Kardo
Kardo

Reputation: 1708

How to show / hide the second div by hovering the first one?

The following code works fine but there is a little problem I couldn't fix.

While div2 is on show, by moving the mouse pointer inside its containing links (from one link to another), it gets hidden.

What's wrong and how to fix?

<html>
<body>
    <script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>

    <div>
        <span id="div1">User Name</span>
        <section id="div2">
            <a id="lnkLogin" href="#">Link 1</a>
            <a id="lnkStatus" href="#">Link 2</a>
        </section>
    </div>
    <script>
        $(function () {
            jQuery('#div2').hide(); jQuery('#div1').mouseover(function () {
                jQuery('#div2').fadeIn();
            });
            jQuery('#div2').mouseout(function () {
                jQuery('#div2').fadeOut();
            });
        });
    </script>
</body>
</html>

Fiddle

Thanks for your attention!

Upvotes: 0

Views: 373

Answers (1)

isherwood
isherwood

Reputation: 61053

Place #div2 inside #div1:

<div> 
    <span id="div1">User Name
        <section id="div2"> 
            <a id="lnkLogin" href="#">Link 1</a>
            <a id="lnkStatus" href="#">Link 2</a>
        </section>
    </span>
</div>

Fiddle demo

Note that I've changed to mouseenter and mouseleave to prevent repetitious behavior. I also suggest semantic ID values instead of element-type values, which become incorrect when your markup changes: #username, #userlinks

Upvotes: 1

Related Questions