Reputation: 2573
I'm trying to animate the margins of a div set by the window height and width.
Please see the fiddle.
The bottom and right margins animate fine on the first click, however left and top do not animate. After first click all margins animate.
Any help would be great.
$( document ).ready(function() {
$("#resizer").height(
$(window).innerHeight()
);
$("#resizer").width(
$(window).innerWidth()
);
});
var xminus = window.innerWidth/15;
var yminus = window.innerHeight/15;
function resizediv(){
var x = $("#resizer").width() - xminus;
var y = $("#resizer").height() - yminus;
var heightoffset = (window.innerHeight - $("#resizer").height())/2
var widthoffset = (window.innerWidth - $("#resizer").width())/2
$("#resizer").animate({
width : x,
height : y,
marginTop : heightoffset,
marginBottom : heightoffset,
marginLeft : widthoffset,
marginRight : widthoffset
}, 1000, function(){
});
}
Upvotes: 1
Views: 129
Reputation: 11506
It's because of the margin you are setting with jquery. Check out margin of the div on each click through browser debugger you will find the error.
You can also set margin auto in the css assigning top, bottom, left, right position 0 in order to have absolute centering of the div and remove margin set from script.
CSS
#resizer{
background-color: white;
position: fixed;
top:0;
bottom:0;
right:0;
left:0;
margin:auto;
padding: 0;
border:1px solid #000;
}
jquery
$( document ).ready(function() {
$("#resizer").height(
$(window).innerHeight()
);
$("#resizer").width(
$(window).innerWidth()
);
});
var xminus = window.innerWidth/15;
var yminus = window.innerHeight/15;
function resizediv(){
var x = $("#resizer").width() - xminus;
var y = $("#resizer").height() - yminus;
var heightoffset = (window.innerHeight - $("#resizer").height())/2
var widthoffset = (window.innerWidth - $("#resizer").width())/2
$("#resizer").animate({
width : x,
height : y
}, 1000, function(){
});
}
Upvotes: 2
Reputation: 52321
You're setting the left margin to:
var widthoffset = (window.innerWidth - $("#resizer").width()) / 2
Originally, the resizer width is the same as the window's width, which means that at the first click, the offset will always be 0, which is causing the element to remain in its position.
On the other hand, width is set to:
$("#resizer").width() - xminus
which means that it will be reduced from the very first click.
Upvotes: 1