How do I toggle the width of a div with animation? My goal is to change the width when I click on the blue div.
$(document).ready(function() {
$('#toggle-button').click(function() {
$('#toggle').toggle(function() {
$('#toggle').animate({
width: "200px"
});
}, function() {
$('#toggle').animate({
width: "300px"
});
});
});
});
#toggle {
height: 200px;
width: 200px;
background: red;
}
#toggle-button {
height: 20px;
width: 20px;
background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="toggle-button"></div>
<div id="toggle"></div>
The issue with your code is due to the use of the (now deprecated)
toggle()event handler. You can implement the logic yourself usingclick(), though:– 2022 Update –
The better approach would now be to toggle the class on successive clicks, using
toggleClass(), and use CSStransitionto animate the width: