Reputation: 67
I have two divs next to each other and would like to use the toggle function to collapse one div (Sidebar) horizontally while expanding the other (Map) to take full width of the former. I would then need the toggle to bring back both divs to their original widths/positions. I can get it to do the first operation but I have no clue on how to do the reverse. See Fiddle:
$(document).ready(function(){
$("#toggle").click(function(){
$("#sidebar").animate({width: 'toggle'});
$("#map").animate({width: '100%'});
});
});
Upvotes: 2
Views: 30469
Reputation: 1613
I usually use a second css class that tells the current status of the div. Something like collapsed
that is changed or removed when the div expands, so you can check for this second class to determine what action the user is requesting.
Fiddle edited: http://jsfiddle.net/8wKxY/6/
Something like this:
$(document).ready(function(){
$("#toggle").click(function(){
if($(this).hasClass('expanded')){
$("#sidebar").stop().animate({width: '19%'});
$("#map").stop().animate({width: '80%'});
$(this).removeClass('expanded');
}
else {
$("#sidebar").stop().animate({width: '100%'});
$("#map").stop().animate({width: '100%'});
$(this).addClass('expanded');
}
});
});
In the example I have attached the control class directly to the button, but it would be more appropriate to attach it to a common container of the two expandable divs.
Also note that you probably need to have an owerflow: hidden
property on the sidebar so that it doesn't goes under the map on collapsing. In my example I completely hide the sidebar after the animation finishes.
Upvotes: 1
Reputation: 20418
Try this
HTML
<input type="button" data-name="show" value="Toggle" id="toggle">
Script
$(document).ready(function () {
$("#toggle").click(function () {
if ($(this).data('name') == 'show') {
$("#sidebar").animate({
width: '0%'
}).hide()
$("#map").animate({
width: '100%'
});
$(this).data('name', 'hide')
} else {
$("#sidebar").animate({
width: '19%'
}).show()
$("#map").animate({
width: '80%'
});
$(this).data('name', 'show')
}
});
});
Upvotes: 5
Reputation: 41832
You just need to check whether the div is 100%
or 80%
.
$(document).ready(function () {
$("#toggle").click(function () {
$("#sidebar").animate({
width: 'toggle'
});
var value = $("#map")[0].style.width !== "100%" ? '100%' : '80%';
$("#map").animate({
width: value
});
});
});
Upvotes: 1
Reputation: 20636
Use jQuery toggleClass()
$(document).ready(function(){
$("#toggle").click(function(){
$("#sidebar").animate({width: 'toggle'});
$("#map").toggleClass('fullWidth');
});
});
.fullWidth{
width : 100% !important;
}
Upvotes: 0