Tamara
Tamara

Reputation: 145

jQuery animate width bigger and smaller at the same time

I would like to hover over a div and make the hovered one bigger and the other one smaller. They are 50% and 50%. What happens when hovering is that the screen is to small for a second and you'll see the content below flickering. What I've done now is set the small div to 29.5% when hovering. Unfortunately this isn't a good solution for me. I would like to use 70% and 30% if possible.

html

<div id="slider">
    <div id="slideLeft">
        <p>Left</p>
    </div>
    <div id="slideRight">
        <p>Right</p>
    </div>
</div>

css

#slider{width:100%;min-height:450px;background-color:#999;}
#slideLeft{width:50%;float:left;background-color:#333;height:450px;}
#slideRight{width:50%;float:left;height:450px;background-color:#666;}

js

$('#slideLeft').mouseenter(function(){
        $("#slideRight").animate({
           width: '30%'
        }, { duration: 200, queue: false });
        $("#slideLeft").animate({
           width: '70%'
        }, { duration: 200, queue: false });
    });
});

Upvotes: 0

Views: 1766

Answers (1)

SpYk3HH
SpYk3HH

Reputation: 22570

After looking at it this morning on a different comp and with different browsers, I found the issue. The issue is the parent being 100%; it needs to have a SET PIXEL width instead. Please see the example below:

jsFiddle

Script

/*  This is simply the same as the document.onLoad func  */
$(function() {
    /*  Grab each element to be animated by a class name  */
    $(".sliders").mouseenter(function() {
        /*  Using .stop helps ensure a smoother animation (no lag backs)  */
        $(this).siblings(".sliders").stop().animate({ width: "30%" }, { duration: 200, queue: false });
        $(this).stop().animate({ width: "70%" }, { duration: 200, queue: false });
    });

    /* with the animation ready (tho you could start your ready func with this,
       set parent slider width on load to be pixals instead of 100 percent  */
    $("#Slider").width($("#Slider").width());
    /*  jQuery reutrns .width as pixels and sets integers as pixels,
        thus the simpl design here will take was initialized by 100% and turn into pixels  */

    /*  And just incase you need to maintain the size on browser window resizing:  */
    $(window).on("resize", function(e) {
        $("#Slider").width("100%");  /* The following line ensures you're set back to pixels
                                        and should elliminate all "flashes"  */
        setTimeout(function() { $("#Slider").width($("#Slider").width()); }, 100);
    });
});

Upvotes: 1

Related Questions