Toggle width with jQuery

The issue with your code is due to the use of the (now deprecated) toggle() event handler. You can implement the logic yourself using click(), though:

$(document).ready(function() {
  $('#toggle-button').click(function() {
    var toggleWidth = $("#toggle").width() == 300 ? "200px" : "300px";
    $('#toggle').animate({ width: toggleWidth });
  });
});
#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>

– 2022 Update –

The better approach would now be to toggle the class on successive clicks, using toggleClass(), and use CSS transition to animate the width:

jQuery($ => {
 $('#toggle-button').on('click', e => {
  $('#toggle').toggleClass('foo');
 });
});
#toggle {
  height: 200px;
  width: 200px;
  background: red;
  transition: width 0.3s;
}

#toggle.foo {
  width: 300px;
}

#toggle-button {
  height: 20px;
  width: 20px;
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="toggle-button"></div>
<div id="toggle"></div>

Leave a Comment