Basj Basj - 7 months ago 10
Javascript Question

Animate a menu using display: flex;

I'd like to animate a menu using

display: flex
with JavaScript (jQuery or vanilla). This doesn't work:



$('#blah').click(function(e){
e.preventDefault();
$('#mid').animate({flex:'0 0 20%'});
return false;
});

* { margin:0; padding: 0; }
#menu { background-color: yellow; display: flex; }
#left {background-color: green; flex: 0 0 200px; }
#mid { background-color: red; flex: 0 0 40%; }
#right {background-color: blue; flex: 1; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="menu">
<div id="left">left green: 200px</div>
<div id="mid">mid red: 40% of browser width</div>
<div id="right">right blue: rest</div>
</div>
<div>
<a href="" id="blah">click here to animate mid to 20%!</a>
</div>





Animate a menu using CSS
display: flex
?

Answer

Use flexBasis in animate functino instead of flex.

$('#blah').click(function(e){
  e.preventDefault(); 
  $('#mid').animate({flexBasis:'20%'});
  return false; 
});
* { margin:0; padding: 0; }
#menu { background-color: yellow; display: flex; }
#left {background-color: green; flex: 0 0 200px; }
#mid { background-color: red; flex: 0 0 40%; }
#right {background-color: blue; flex: 1; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="menu">
  <div id="left">left green: 200px</div> 
  <div id="mid">mid red: 40% of browser width</div> 
  <div id="right">right blue: rest</div>
</div>
<div>
<a href="" id="blah">click here to animate mid to 20%!</a>
</div>

Comments