Search code examples
jquerycssslidetogglemouseenter

jquery, issue with mouseEnter and slideToggle


I made a little jquery script, when the mouse is over a div .frame, it is slidetoggleing two divs: .contentTop and .contentBottom It's working well but I have some issues when I'm applying the script to 2 divs, first when I'm moving really fast the mouse from one div .frame to the other one it mess the script, then when the mouse is over .frame I would like .contentBottom to be over the other.frame

my css are:

    .frame{
    background-color: #FFFFFF;
    position:relative;
    width:40%;
}


.contentTop { 
    position:absolute;
    display:none;
    background-color: #FFFFFF;
}

.contentBottom { 
    position:absolute;
    background-color: #FFFFFF;
    display: none;
}

and my jquery:

$(document).on('mouseenter', '.frame', function() {
    var el = $(this);
    var hauteur = el.height();
    var largeur = el.width();
    contentBottom = el.children(".contentBottom");
    contentTop = el.children(".contentTop");
    contentTop.css({"bottom":hauteur,"width":largeur}); 
    contentTop.html('top top top top');
    contentBottom.html('bottom bottom bottom bottom<br>bottom bottom bottom bottom<br>bottom bottom bottom bottom<br>bottom bottom bottom bottom<br>');
    contentBottom.css({"top":hauteur,"width":largeur});
    contentBottom.stop(true, true).slideToggle(300);
    contentTop.stop(true, true).slideToggle(300);   
}).on('mouseleave','.frame', function() {
    var el = $(this);
    contentBottom = el.children(".contentBottom");
    contentTop = el.children(".contentTop");
    contentTop.stop(true, true).slideToggle(300, function(){
        contentTop.html('');
    });
    contentBottom.stop(true, true).slideToggle(300, function(){
        contentBottom.html('');
    });
});

I made a jsfiddle here: http://jsfiddle.net/malamine_kebe/2ANkq/2/


Solution

  • All you need: LIVE DEMO

    $(document).on('mouseenter mouseleave', '.frame', function( e ) {
    
        var $el=$(this),
            h = $el.height(),
            w = $el.width(),
            $bott = $el.find(".contentBottom"),
            $top  = $el.find(".contentTop"),
            mEnt  = e.type == "mouseenter"; // boolean
    
        // this
        $el.stop().animate({borderRadius: mEnt? 0 : 3 });
    
        // top
        $top.css({bottom: h, width: w, zIndex:1})
            .html('top top top top')
            .stop().slideToggle(function(){
                 $(this).css({zIndex:0});
            });
    
        // bottom    
        $bott.css({top: h, width: w,  zIndex:1})
             .html('bottom bottom bottom bottom<br>bottom bottom bottom bottom<br>bottom bottom bottom bottom<br>bottom bottom bottom bottom<br>')
             .stop().slideToggle(function(){
                 $(this).css({zIndex:0});
             });
    
    });
    

    Note: .stop() method, and mEnt boolean variable and it's use with Conditional Operator statement ? ifTrue : ifFalse