Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle width with jQuery

Tags:

jquery

How do I toggle the width of a div with animation?

HTML:

<div id="toggle-button"></div>
<div id="toggle"></div>​

css:

#toggle{
  height:200px;
  width:200px;
  background:red;
}
#toggle-button{
  height:20px;
  width:20px;
  background:blue;
}

jQuery:

$(document).ready( function(){
  $('#toggle-button').click( function() {
    $('#toggle').toggle(function() {
      $('#toggle').animate({width:"200px"});
    }, function() {
      $('#toggle').animate({width:"300px"});
    });
  });
});​

Example that doesn't work: http://jsfiddle.net/ZfHZV/1/

Edit: My goal is to change the width when I click on the blue div

like image 702
Puyol Avatar asked May 28 '12 08:05

Puyol


2 Answers

Try this:

$(document).ready( function(){
    $('#toggle-button').click( function() {
        var toggleWidth = $("#toggle").width() == 300 ? "200px" : "300px";
        $('#toggle').animate({ width: toggleWidth });
    });
});

Example fiddle

like image 146
Rory McCrossan Avatar answered Sep 24 '22 15:09

Rory McCrossan


Dude! your code works, you just don't understand what it does...

  $('#toggle-button').click( function() { // Execute when the toggle button is clicked.
    $('#toggle').toggle(function() {      // Attach toggle function that fire different
                                          // callback when clicked.
      $('#toggle').animate({width:"200px"});
    }, function() {
      $('#toggle').animate({width:"300px"});
    });
  });

Click on the blue div and then on the red div couple of time and see how it works.

Note that you better attach the toggle click callbacks with one instead of click to avoid multiple callback of clicks:

  $('#toggle-button').one('click', function() {
    $('#toggle').toggle(function() {
        $('#toggle').animate({width:"200px"});
    }, function() {
        $('#toggle').animate({width:"300px"});
    });
  });

Live DEMO

like image 30
gdoron is supporting Monica Avatar answered Sep 24 '22 15:09

gdoron is supporting Monica