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
Try this:
$(document).ready( function(){
$('#toggle-button').click( function() {
var toggleWidth = $("#toggle").width() == 300 ? "200px" : "300px";
$('#toggle').animate({ width: toggleWidth });
});
});
Example fiddle
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With