Reputation: 92581
I have a fixed position div with a fixed height/width.
The div is positioned using
position: fixed;
left = 50%; margin-left = -(width/2) top = 50%; margin-top: = -(width/2)
The div has a black background.
What I want to do is, when a button is pressed calculate the size of the new contents (hidden dom element)
Fade the contents of the div out, animate it resizing to the new contents size (staying centered).
Fade the new contents in.
What is the easiest way to do this with jQuery?
Upvotes: 1
Views: 2885
Reputation: 228152
Try this: http://jsfiddle.net/EpzDM/
It works, but I don't doubt the JavaScript could be improved.
JavaScript:
var $box = $('#box');
var $boxInner = $box.find(' > div');
var fixIt = function() {
var newWidth = 300;
var newHeight = 150;
$boxInner.fadeOut(function() {
$box.animate({
marginLeft: -newWidth/2,
marginTop: -newHeight/2,
width: newWidth,
height: newHeight
}, 500, function() {
$boxInner.fadeIn();
});
});
};
$(window).resize(function() {
$box.css({
marginLeft: -$box.width()/2,
marginTop: -$box.height()/2
});
}).resize();
$('<button>Clicky!</button>').appendTo(document.body).click(fixIt).css({
position: 'fixed',
top: 0,
left: 0
});
CSS:
#box {
width: 200px;
height: 100px;
background: #ccc;
position: fixed;
left: 50%;
top: 50%
}
HTML:
<div id="box">
<div>
<p>Contents of div</p>
<p>Contents of div</p>
<p>Contents of div</p>
</div>
</div>
Upvotes: 0
Reputation: 15835
you can do this one also
this=$('#yourDiv');
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
This is from one of my applications , try and it should center it
refactor if you need any customization.
function centerPopup() {
var windowWidth = document.body.clientWidth;
var windowHeight = document.body.clientHeight;
var popupHeight = $('#popupplaceholder').height();
var popupWidth = $('#popupplaceholder').width();
if (popupWidth > windowWidth) {
popupWidth = (windowWidth) * (0.9);
}
if (popupHeight > windowHeight) {
popupHeight = (windowHeight) * (0.9);
}
//centering
var objControl = document.getElementById("yourDIV");
if (objControl != null) {
if (objControl.offsetParent != null) {
var left = (objControl.offsetParent.clientWidth / 2) - (objControl.clientWidth / 2) + objControl.offsetParent.scrollLeft;
var top = (objControl.offsetParent.clientHeight / 2) - (objControl.clientHeight / 2) + objControl.offsetParent.scrollTop;
$('#yourDIV').css({
"position": "absolute",
"top": top,
"left": left
});
}
}
}
Upvotes: 0