views:

60

answers:

2

Consider the following code:

HTML:

<div class='a'></div>
<div class='b'></div>

CSS:

body {
    position: relative;
}
.a {
    position: absolute;
    left: 100px;
    top: 100px;
    width: 100px;
    height: 100px;
    background: #777;
}
.b {
    position: absolute;
    display: none;
    background: red;
}

JavaScript:

$(function() {
    $('.a').live('mouseover mouseout', function(e) {
        switch (e.type) {
            case 'mouseover': {
                $('.b').offset({'left': $(this).offset().left,
                                'top': $(this).offset().top})
                       .width($(this).outerWidth())
                       .height($(this).outerHeight())
                       .show();
                break;
            }       
            case 'mouseout': {
                $('.b').hide();
                break;
            }        
        }
    });
});

As you can see here, some kind of flickering occurs, because when .b is shown, mouseout automatically occurs. How would you solve this problem ?

The desired behavior is: when the mouse is over .a, .b should be shown (should cover .a), and when the mouse is not over .a, .b should not be shown. .a should always be shown.

The position and dimensions of .a is not constant (should be calculated on the fly).

+3  A: 

I come up with this solution:

$(function() {
    $('.a').live('mouseover', function(e) {
        $('.b').offset({'left': $(this).offset().left,
                        'top': $(this).offset().top})
               .width($(this).outerWidth())
               .height($(this).outerHeight())
               .show();
    });
    $('.b').live('mouseout', function(e) {
        $(this).hide();
    });
});
Misha Moroshko
change `$('.b').offset` to `$('.b').css` when setting position. otherwise this works.
lincolnk
A: 

Try

$(function() {
    $('.a').live('mouseover', function(e) {
        $('.b').offset({'left': $(this).offset().left,
                        'top': $(this).offset().top})
                .width($(this).outerWidth())
                .height($(this).outerHeight())
                .show();
    });
    $('.b').live('mouseout', function(e) {
        $('.b').hide();
        break;
    });
});

This should mean that when the user moves thier mouse over area a, area b is shown and then when they move thier mouse out of area b, area a is reshown.

Lee
This is exactly the solution that I came up with :) But not, I think it is not good enough, because the dimensions of `.b` can be different from those of `.a`. Do you have any other idea ?
Misha Moroshko