Question

My container div contain two divs div box1 and div box2. box2 is absolute div with max width of 400px;

html:

<div id="container">
<div class="box1"></div>
<div class="box2 animated"></div>
</div>

css:

#container{position:relative;width:100%;height:100%;background:red;} 

#container #box1{position:relative;width:760px;height:300px;background:blue;margin:0;} 

#container #box2{position:absolute;width:60px;max-width:350px;height:300px;background:yellow;;top:0;} 

jQuery:

 $(document).ready(function(){
    var box1width = $(".box1").width();
    var windowWidth = $(window).width();
    var x = windowWidth - (box1width + 350 ) ;
    var wdt = windowWidth - (box1width) ;


    if (".box2").hasClass("animated"){
       if(x > windowWidth ){
       $(".box2").animate({width:'350px'}, 2000); 
       } else { 
       $(".box2").animate({width: wdt+ 'px'}, 2000);
       } 
    } else {

    alert("no animation for box2 nd width remain 60px");
    }

    });

Initially this animate my box2width;Now I want to animate box2 width on window resize as well as limit my box2 animate width upto 350px only;

Was it helpful?

Solution

Check this Fiddle

if (!$(".box2").hasClass("animated")) {
     if (wdt >= 60) {
         $(".box2").animate({
             width: '350px'
         }, 2000);
         $(".box2").addClass('animated');
     }
 } else {
         if (wdt <= 350) {
             $(".box2").css('width','60px');
             $(".box2").removeClass('animated');
         }
     }

side note: not sure if this is exactly what you want, if not comment below :)

update as per comments updated fiddle

$(document).ready(function () {
 anime();
 var resizeTimer;
 window.onresize = function () {
     if (resizeTimer) {
         clearTimeout(resizeTimer);
     }
     resizeTimer = setTimeout(function () {
         anime();
     }, 200);
 }
})
 function anime() {
 var windowWidth = $(window).width();
 var box1width = $(".box1").width();
 var wdt = windowWidth - (box1width);
 if (wdt > 60) {
     $(".box2").stop(true,true).animate({
         width: wdt
     }, 1000);
     $(".box2").addClass('animated');
 } else if($(".box2").hasClass('animated')){
   $(".box2").css('width', '60px');
   $(".box2").removeClass('animated');
 }
}

Note: this is just a fix for what you're trying to do, i'd prefer css3 transition over this..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top