JQuery: best way to place dom element in center of view
I'm looking for a suitable way to position the floating div element in the center of the current viewport.
For example: we have a div element with {display:none; position:absolute}
and several buttons, one at the top of the document, the second in the center, and the last one somewhere at the bottom. By clicking on any of these buttons, the div should appear in the center of the current viewport.
$(".btnClass").click(function(){
//some actions for positioning here
$(div_id).show()
})
a source to share
The following will do it. Although there are other ways (using CSS, margins, overflows, etc) ... so this may not be the answer to your question depending on what you think is "best".
$(".btn_class").click(function(){
var win = $(window),
winW = win.width(),
winH = win.height(),
scrollTop = win.scrollTop(),
scrollLeft = win.scrollLeft(),
container = $("#div_id").css({"display":"block","visibility":"hidden"}),
contW = container.width(),
contH = container.height(),
left = (winW-contW)/2+scrollLeft,
top = (winH-contH)/2+scrollTop;
container.css({"left":left,"top":top,"visibility":"visible"});
});
You may need to adjust scrollLeft and scrollTop ... I am distracted and cannot think (sigh, I wish I had my own personal account).
a source to share