Reputation: 51
I would like to be able to allow the user to click a button which shows a div to the right of the div which is already present. Here's a Fiddle of where I am http://jsfiddle.net/AV2mZ/.
As you can see when both divs are present, after clicking "slide it", everything stays where its supposed to be. But when the window is resized everything messes up. I've tried to solve this puzzle myself but lack the knowledge.
Any help is welcome, the more in depth the better.
Thanks!
<div id="change">
<div style="width:56px;height:56px;position:absolute;background:#999;left:0;top:0;">Stay?</div>
<div style="width:56px;height:56px;position:absolute;background:#999;right:0;top:0;">Stay?</div>
</div>
<div id="right" style="width:300px;height:100%;background:#000;position:fixed;right:-300px;">
</div>
<br><br><br><br><br><br><br><br>
<button id="toggle">slide it</button>
$('button').live("click",function() {
$('#change').animate({
width: $('#change').width()-$('#right').width()
}, 300);
$('#right').animate({
right: "0"
}, 300);
return false;
});
$(window).resize(function() {alert($('#change').width()-$('#right').width());
$('#change').animate({
width: $('#change').width()-$('#right').width()
}, 300);
});
Upvotes: 1
Views: 181
Reputation: 950
You should just not use the width of #change when you want to set it since it you will change it. For example you click on "slide it" so the width it now "initWidth - 300". Then you resize the window, the the width will be now "initWidth - 300 - 300" and so on.
To make your example works, you can use the width of body instead:
$('#change').animate({
width: $('body').width()-$('#right').width()
}, {duration: 300, queue: false});
Upvotes: 1