Dynamically Resizing Image Maps? - javascript

Hope you can help with this problem I've been trying to nut out.
I've found the examples on http://home.comcast.net/~urbanjost/semaphore.html very awesome and work perfectly for what I need.
Only problem is that I'd like the coordinates to dynamically change based on the window size first. The way it works at the moment is that it loads the default coords (works great for resolutions of 1920x1080 but is hugely unaligned on 1024x768) and will then resize on window resize.. I'd like it to detect the size of the browser window for smaller screens first, then display the code accordingly.
Here's my javascript:
<script type="text/javascript" >
//||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||||||||||||
GLOBAL_AREAS= new Array();
GLOBAL_SUFFIX= "g";
GLOBAL_WIDTH=-1;
GLOBAL_HEIGHT=-1;
GLOBAL_NEW_AREAS= new Array();
//---------------------------------------------------------------------------
function setglobal(){
// place original AREA coordinate strings into a global array, called first time setXY is called
var arrayAreas = document.body.getElementsByTagName("AREA" );
GLOBAL_WIDTH= document.getElementById("tclteam_s1" ).width; // get original width
GLOBAL_HEIGHT= document.getElementById("tclteam_s1" ).height; // get original height
for(var i = 0; i < arrayAreas.length; i++) {
GLOBAL_AREAS[i]= arrayAreas[i].coords;
}
document.body.onresize=setXY('tclteam_s1',XSIZE(),YSIZE());
// alert("GLOBAL_AREAS" + GLOBAL_AREAS );
}
//---------------------------------------------------------------------------
function setXY(elementid,newwidth,newheight){
if (GLOBAL_WIDTH == -1 ){
setglobal();
}
document.getElementById(elementid).width=newwidth;
document.getElementById(elementid).height=newheight;
scaleArea();
}
//---------------------------------------------------------------------------
function XSIZE(){ // get browser window.innerWidth , dealing with ie
var myWidth = 1;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
} else if( document.documentElement && ( document.documentElement.clientWidth ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
} else if( document.body && ( document.body.clientWidth ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
}
return myWidth;
}
//---------------------------------------------------------------------------
function YSIZE(){ // get browser window.innerHeight, dealing with ie
var myHeight = 1;
if( typeof( window.innerHeight ) == 'number' ) {
//Non-IE
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientHeight ) ) {
//IE 4 compatible
myHeight = document.body.clientHeight;
}
return myHeight;
}
//---------------------------------------------------------------------------
function scaleArea() { // using values stored at load, recalculate new values for the current size
var arrayAreas = document.body.getElementsByTagName("AREA" );
message = " "
for(var i = 0; i < arrayAreas.length; i++) {
ii=i+1;
rescaleX= document.getElementById("tclteam_s1" ).width/GLOBAL_WIDTH ;
rescaleY= document.getElementById("tclteam_s1" ).height/GLOBAL_HEIGHT ;
sarray=GLOBAL_AREAS[i].split("," ); // convert coordinates to a numeric array assuming comma-delimited values
var rarray =new Array();
for(var j = 0; j < sarray.length; j += 2) {
rarray[j]=parseInt(sarray[j])*rescaleX; // rescale the values
rarray[j]=Math.round(rarray[j]);
rarray[j+1]=parseInt(sarray[j+1])*rescaleY; // rescale the values
rarray[j+1]=Math.round(rarray[j+1]);
}
message = message + rarray.join("," ) + '\n';
arrayAreas[i].coords=rarray.join("," ); // put the values back into a string
GLOBAL_NEW_AREAS[i]= arrayAreas[i].coords;
}
// alert(rescaleX + " " + rescaleY + "\n" + GLOBAL_WIDTH + " " + GLOBAL_HEIGHT + "\n" + " GLOBAL_AREAS" + GLOBAL_AREAS + "\nSCALED AREAS" + message);
}
//||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
</script>
The following script here detects the browser window size. So I'm hoping to include this in the above so the image map will dynamically resize from the browser window size first:
<script type="text/javascript">
var winW = 630, winH = 460;
if (document.body && document.body.offsetWidth) {
winW = document.body.offsetWidth;
winH = document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
winW = document.documentElement.offsetWidth;
winH = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
winW = window.innerWidth;
winH = window.innerHeight;
}
</script>
Is there a way to code this so it will read the browser window size first (using the code directly above), then load the image map accordingly?

Related

live browser size detection

This code only works based on the size of the browser at the time of loading, just wondering what could I implement for it get the current browser size and work based on that current information.
I have tried wrapping it in resize() but it causes it behave strangely, i.e the toggle goes on and off continuously , or when loading in a shrunk browser it doesnt work at all.
Its a responsive site where the footer menu is just static links on a large screen but turns into drop menu on small screen.
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
if(myWidth < 980) {
$("#footer h3").click(function () {
$(this).toggleClass("active");
$(this).parent().find("ul").slideToggle('medium');
});
}
var myWidth = 0, myHeight = 0;
function getSize(){
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
}
getSize(); // run first time
$(window).resize(function(){
getSize(); // do it on resize
});
$("#footer h3").click(function () {
getSize(); // not needed but good to have
if(myWidth < 980) {
$(this).toggleClass("active");
$(this).parent().find("ul").slideToggle('medium');
}
});
You should use css media queries instead:
#media only screen and (max-device-width: 980px) {
// css goes here...
}
OR include conditional style sheets:
<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="small-device.css" />
Here is a great article disusing responsive design
Try something like this:
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) uniqueId = "Don't call this twice";
if (timers[uniqueId]) clearTimeout (timers[uniqueId]);
timers[uniqueId] = setTimeout(callback, ms);
};
})();
$(window).resize(function(){
waitForFinalEvent(function(){
// put all your code here
}, 20, "resize"); // replace 20 with every milliseconds to execute during
// resize
})
The code you put in there will execute every time the window resizes, simply using resize() won't always work because it doesn't necessarily check as you're resizing.

Animation flickers with Firefox 18.0.1 (due to RequestAnimationFrame?)

i used this http://www.netmagazine.com/tutorials/create-interactive-street-view-jquery tutorial to create an intro for one of our customers:
http://f-bilandia.de/kunstmann/bronski/
It used to work really good on all browsers. When I updated to the newest stable version of Firefox (FF 18.0.1) however, there is heavy flickering while changing the images.
When reading the release notes of the newest version, i saw that ff has a new Javascript engine and has improved image quality with a new HTML scaling algorithm. Maybe it's because of that? Other possible solutions?
Below you can see the code i've used:
$(document).ready(function(){
var $doc = $(document);
var $win = $(window);
// dimensions - we want to cache them on window resize
var windowHeight, windowWidth;
var fullHeight, scrollHeight;
var streetImgWidth = 1024, streetImgHeight = 640;
calculateDimensions();
var currentPosition = -1, targetPosition = 0;
var $videoContainer = $('.street-view');
var video = $('.street-view > img')[0];
var $hotspotElements = $('[data-position]');
// handling resize and scroll events
function calculateDimensions() {
windowWidth = $win.width();
windowHeight = $win.height();
fullHeight = $('#main').height();
scrollHeight = fullHeight - windowHeight;
}
function handleResize() {
calculateDimensions();
resizeBackgroundImage();
handleScroll();
}
function handleScroll() {
targetPosition = $win.scrollTop() / scrollHeight;
}
// main render loop
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
function animloop(){
if ( Math.floor(currentPosition*5000) != Math.floor(targetPosition*5000) ) {
currentPosition += (targetPosition - currentPosition) / 5;
render(currentPosition);
}
requestAnimFrame(animloop);
}
// rendering
function render( position ) {
// position the elements
var minY = -windowHeight, maxY = windowHeight;
$.each($hotspotElements,function(index,element){
var $hotspot = $(element);
var elemPosition = Number( $hotspot.attr('data-position') );
var elemSpeed = Number( $hotspot.attr('data-speed') );
var elemY = windowHeight/2 + elemSpeed * (elemPosition-position) * scrollHeight;
if ( elemY < minY || elemY > maxY ) {
$hotspot.css({'visiblity':'none', top: '-1000px','webkitTransform':'none'});
} else {
$hotspot.css({'visiblity':'visible', top: elemY, position: 'fixed'});
}
});
renderVideo( position );
}
function resizeBackgroundImage(){
// get image container size
var scale = Math.max( windowHeight/streetImgHeight , windowWidth/streetImgWidth );
var width = scale * streetImgWidth , height = scale * streetImgHeight;
var left = (windowWidth-width)/2, top = (windowHeight-height)/2;
$videoContainer
.width(width).height(height)
.css('position','fixed')
.css('left',left+'px')
.css('top',top+'px');
}
// video handling
var imageSeqLoader = new ProgressiveImageSequence( "street/vid-{index}.jpg" , 387 , {
indexSize: 4,
initialStep: 16,
onProgress: handleLoadProgress,
onComplete: handleLoadComplete,
stopAt: 1
} );
// there seems to be a problem with ie
// calling the callback several times
var loadCounterForIE = 0;
imageSeqLoader.loadPosition(currentPosition,function(){
loadCounterForIE++;
if ( loadCounterForIE == 1 ) {
renderVideo(currentPosition);
imageSeqLoader.load();
imageSeqLoader.load();
imageSeqLoader.load();
imageSeqLoader.load();
}
});
var currentSrc, currentIndex;
function renderVideo(position) {
var index = Math.round( currentPosition * (imageSeqLoader.length-1) );
var img = imageSeqLoader.getNearest( index );
var nearestIndex = imageSeqLoader.nearestIndex;
if ( nearestIndex < 0 ) nearestIndex = 0;
var $img = $(img);
var src;
if ( !!img ) {
src = img.src;
if ( src != currentSrc ) {
video.src = src;
currentSrc = src;
}
}
}
$('body').append('<div id="loading-bar" style="">Loading...</div>');
function handleLoadProgress() {
var progress = imageSeqLoader.getLoadProgress() * 100;
$('#loading-bar').css({width:progress+'%',opacity:1});
}
function handleLoadComplete() {
$('#loading-bar').css({width:'100%',opacity:0,display: "none"});
$("html, body").css("overflow", "auto");
$("html, body").css("overflow-x", "hidden");
$("nav").css("display", "block");
$("#preloader").fadeOut("slow");
$("#scroll-hint").css("display", "block");
}
$win.resize( handleResize );
$win.scroll( handleScroll );
handleResize();
animloop();
});
Inside your "render( position )" function the following lines seem like they should be refactored.
if ( elemY < minY || elemY > maxY ) {
$hotspot.css({'visiblity':'none', top: '-1000px','webkitTransform':'none'});
} else {
$hotspot.css({'visiblity':'visible', top: elemY, position: 'fixed'});
}
For one visibility is spelled wrong and there is no "none" value for it (it would be "hidden"). Just use "display" with "none" and "" values.
The "top", "webkitTransform", and "position" keys seem unnecessary. If the element is not visible there's no need to set the top, and why wouldn't the element always be fixed position?

Prevent Javascript from continuing a function if the screen is lower than 480 pixels

First of all, I'm not a javascript expert. I'm going crazy on trying to figure out how to make a conditional execution of a certain javascript. I'm using JQuery to absolutely center my block in a browser page, but only if the screen size is bigger than 480px (In other meaning, I don't want this script to run on smartphones). I'm using CSS media query to indicate my request. The thing is, this script works fine on all smartphones, Safari 5+, IE10, Firefox 13. BUT IT DOESN'T WORK ON IE6-9 and Opera 12 (As far as I understand, they don't support transitions). CAN ANYONE PLEASE HELP ME FIGURE OUT WHAT I AM DOING WRONG? And if there's a better way of doing this? (I tried #media query in CSS but The script keeps on running no matter what)... I would really appreciate the help.
<script>
if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
event.preventDefault();
} else{
//Absolute Content Center
function CenterItem(theItem){
var winWidth=$(window).width();
var winHeight=$(window).height();
var windowCenter=winWidth/2;
var itemCenter=$(theItem).width()/2;
var theCenter=windowCenter-itemCenter;
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winWidth>$(theItem).width()){ //horizontal
$(theItem).css('left',theCenter);
} else {
$(theItem).css('left','0');
}
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
$(document).ready(function() {
CenterItem('.content');
});
$(window).resize(function() {
CenterItem('.content');
});
} //end of "else" (normal execution)
</script>
You can try this :-
<script>
var screenWidth = screen.width;
if (screenWidth > 480 ) {
//Absolute Content Center
function CenterItem(theItem){
var winWidth=$(window).width();
var winHeight=$(window).height();
var windowCenter=winWidth/2;
var itemCenter=$(theItem).width()/2;
var theCenter=windowCenter-itemCenter;
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winWidth>$(theItem).width()){ //horizontal
$(theItem).css('left',theCenter);
} else {
$(theItem).css('left','0');
}
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
$(document).ready(function() {
CenterItem('.content');
});
$(window).resize(function() {
CenterItem('.content');
});
}
</script>
To get exact Height and Width in all browser is quite big deal because of IE, But no worries is the solution for all Browser including IE 6 to latest.
Here are those 2 function:
if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
event.preventDefault();
} else{
//Absolute Content Center
$(document).ready(function() {
CenterItem('.content');
});
$(window).resize(function() {
CenterItem('.content');
});
} //end of "else" (normal execution)
function CenterItem(theItem){
var winWidth=getWindowWidth();
var winHeight=getWindowHeight();
var windowCenter=winWidth/2;
var itemCenter=$(theItem).width()/2;
var theCenter=windowCenter-itemCenter;
var windowMiddle=winHeight/2;
var itemMiddle=$(theItem).height()/2;
var theMiddle=windowMiddle-itemMiddle;
if(winWidth>$(theItem).width()){ //horizontal
$(theItem).css('left',theCenter);
} else {
$(theItem).css('left','0');
}
if(winHeight>$(theItem).height()){ //vertical
$(theItem).css('top',theMiddle);
} else {
$(theItem).css('top','0');
}
}
function getWindowHeight() {
var myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myHeight = document.body.clientHeight;
}
return myHeight;
}
function getWindowWidth() {
var myWidth = 0;
if( typeof( window.innerWidth ) == 'number' ) {
myWidth = window.innerWidth;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
myWidth = document.documentElement.clientWidth;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
myWidth = document.body.clientWidth;
}
return myWidth;
}
This will help you to get exact height in any Browser, in that way you can apply your logic. Hope this help!!!
Simplest thing is not to attach the event handler if the media query does not match.
$.fn.extend({
centerItem: function () {
return this.each(function () {
var $this = $(this),
hCenter = ( $(window).width() - $this.width() ) / 2,
vCenter = ( $(window).height() - $this.height() ) / 2;
$this.css({
left: hCenter > 0 ? hCenter : 0,
top: vCenter > 0 ? vCenter : 0
});
});
}
});
$(function() {
var bigScreen = 'only screen and (max-device-width:800px) and (orientation: portrait)';
if ( matchMedia(bigScreen).matches ) {
$(window).resize(function() {
$('.content').centerItem();
});
}
});
Notes
$() replaces $(document).ready(). See http://api.jquery.com/ready/
By convention, only object constructors start with a capital letter, so your CenterItem() function should actually be called centerItem().
I've turned your function into a jQuery plugin. You can of course continue using your own implementation if you find that confusing.
The .css() function can take an object argument so you can set multiple CSS properties in one step.
I've used the ternary operator (expression ? ifTrue : ifFalse) to replace the if.
You can do
window.innerHeight
window.innerWidth
to get the dimensions of the viewport. Now you could do:
var width = window.innerWidth
if (width > 480){
/* do desktop stuff*/
}
As alternative, you could go for the UserAgentString and/or Operating with:
window.navigator
(more reliable Detect-script)
However, either attempt might fail in some cirumstances.
edit: would be nice if you posted your match-media function.
edit2: use the script for correct viewport detection: https://stackoverflow.com/a/2035211/1047823
and then alter your code:
if ( getViewport()[0] < 480 ) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
event.preventDefault();
} else{
// your desktop code
}

Get page height in JS (Cross-Browser)

What is the best way to get the actual page (not window) height in JS that is cross-browser compatible?
I've seen a few ways but they all return different values...
self.innerHeight
or
document.documentElement.clientHeight
or
document.body.clientHeight
or something else?
One way of doing it which seems to work is :
var body = document.body,
html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
Page/Document height is currently subject to vendor (IE/Moz/Apple/...) implementation and does not have a standard and consistent result cross-browser.
Looking at JQuery .height() method;
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ],
body = elem.document.body;
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
body && body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
nodeType === 9 mean DOCUMENT_NODE : http://www.javascriptkit.com/domref/nodetype.shtml
so no JQuery code solution should looks like:
var height = Math.max(
elem.documentElement.clientHeight,
elem.body.scrollHeight, elem.documentElement.scrollHeight,
elem.body.offsetHeight, elem.documentElement.offsetHeight)
var width = window.innerWidth ||
html.clientWidth ||
body.clientWidth ||
screen.availWidth;
var height = window.innerHeight ||
html.clientHeight ||
body.clientHeight ||
screen.availHeight;
Should be a nice & clean way to accomplish it.
Try this without jQuery
//Get height
var myWidth = 0, myHeight = 0;
if (typeof (window.innerWidth) == 'number') {
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
Hope this helps you.

jQuery Alignment - Relative to Browser Window?

With help from various websites, I've created a very simple pop-up box using javascript that contains my contact information. I'm happy with how it works, except that the popup window that appears is positioned absolutely, and I want to have it appear relative to the browser window (ie I want the pop up to appear in the centre of the browser window, regardless of where you are on the page when you click the info icon).
I'm comfortable with HTML, but not with javascript. I know that relative positioning works very differently in javascript, but I cannot get my head around how to fix this. Any advice would be appreciated.
The webpage is here: http://www.thirstlabmedia.com/
The script is as follows:
<script type="text/javascript">
function toggle( div_id ) {
var el = document.getElementById( div_id );
if( el.style.display == 'none' ) {
el.style.display = 'block';
}
else {
el.style.display = 'none';
}
}
function blanket_size( popUpDivVar ) {
if( typeof window.innerWidth != 'undefined' ) {
viewportheight = window.innerHeight;
}
else {
viewportheight = document.documentElement.clientHeight;
}
if( ( viewportheight > document.body.parentNode.scrollHeight ) && ( viewportheight > document.body.parentNode.clientHeight ) ) {
blanket_height = viewportheight;
}
else {
if( document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight ) {
blanket_height = document.body.parentNode.clientHeight;
}
else {
blanket_height = document.body.parentNode.scrollHeight;
}
}
var blanket = document.getElementById( 'blanket' );
blanket.style.height = blanket_height + 'px';
var popUpDiv = document.getElementById( popUpDivVar );
popUpDiv_height = window.innerHeight / 2 - 200;
popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos( popUpDivVar ) {
if( typeof window.innerWidth != 'undefined' ) {
viewportwidth = window.innerHeight;
}
else {
viewportwidth = document.documentElement.clientHeight;
}
if( ( viewportwidth > document.body.parentNode.scrollWidth ) && ( viewportwidth > document.body.parentNode.clientWidth ) ) {
window_width = viewportwidth;
}
else {
if( document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth ) {
window_width = document.body.parentNode.clientWidth;
}
else {
window_width = document.body.parentNode.scrollWidth;
}
}
var popUpDiv = document.getElementById( popUpDivVar );
window_width = window_width / 2 - 200;
popUpDiv.style.left = window_width + 'px';
}
function popup( windowname ) {
blanket_size( windowname );
window_pos( windowname );
toggle( 'blanket' );
toggle( windowname );
}
</script>
(My apologies for placing it all on one line; the website is created through Cargo Collective, and it doesn't accept script unless it's all placed on one line).
Use CSS position : fixed:
#my-element {
position : fixed;
top : 50%;
left : 50%;
margin : -100px 0 0 -250px;
width : 500px;
height : 200px;
z-index : 1000;
}
Here is a demo: http://jsfiddle.net/huRcV/1/
This centers a 500x200px element in the viewport. The negative margins are used to center the element with respect to its dimensions. If the user scrolls the page, the element will stay centered in the viewport.
Docs for position: https://developer.mozilla.org/en/CSS/position
fixed
Do not leave space for the element. Instead, position it at a
specified position relative to the screen's viewport and doesn't move
when scrolled. When printing, position it at that fixed position on
every page.
You can do this with JavaScript but it's probably better to use the CSS version. If you do want to use jQuery here is a quick example:
var $myElement = $('#my-element');
$(window).on('scroll resize', function () {
$myElement.css({
top : ($(this).scrollTop() + ($(this).height() / 2)),
});
});
Here is a demo: http://jsfiddle.net/huRcV/ (notice that position : fixed is changed to position : absolute for this demo)

Categories