Centering a DIV in viewport with JavaScript - javascript

I am trying to center a DIV in screen using below code but it is not working for me. Someone please suggest me to make it work
var hnw = {};
hnw.w = 0;
hnw.h = 0;
if (!window.innerWidth) {
if (!(document.documentElement.clientWidth == 0)) {
hnw.w = document.documentElement.clientWidth;
hnw.h = document.documentElement.clientHeight;
}
else {
hnw.w = document.body.clientWidth;
hnw.h = document.body.clientHeight;
}
}
else {
hnw.w = window.innerWidth;
hnw.h = window.innerHeight;
}
var midEle = document.createElement('div');
var _x = 0;
var _y = 0;
var offsetX = 0;
var offsetY = 0;
if (!window.pageYOffset) {
if (!(document.documentElement.scrollTop == 0)) {
offsetY = document.documentElement.scrollTop;
offsetX = document.documentElement.scrollLeft;
}
else {
offsetY = document.body.scrollTop;
offsetX = document.body.scrollLeft;
}
}
else {
offsetX = window.pageXOffset;
offsetY = window.pageYOffset;
}
midEle.style.width = "300px";
midEle.style.height = "300px";
midEle.innerHTML = "Some Text";
midEle.style.display = "block";
var _x_w = parseInt(midEle.style.width, 10), _y_h = parseInt(midEle.style.height, 10);
_x = ((hnw.w - _x_w) / 2) + offsetX;
_y = ((hnw.h - _y_h) / 2) + offsetY;
console.log(_x, " ", _y);
midEle.style.position = "absolute";
midEle.style.left = _x;
midEle.style.top = _y;
document.body.appendChild(midEle);

Can't this be done with CSS instead?
Javascript:
var midEle = document.createElement('div');
midEle.className = 'centered';
document.body.appendChild(midEle);
​CSS:
​.centered{
background-color: red;
height: 300px;
width: 300px;
margin: -150px 0 0 -150px;
top: 50%;
left: 50%;
position: fixed;
}​
http://jsfiddle.net/FkEyy/3/
By setting the margins to the negative half of the elements height and width, and setting top and left values to 50%, you'll center the element. This is a common way of centering content with CSS :)

For left and top style properties px was missing. Values must be either px or %
Change
midEle.style.left = _x;
midEle.style.top = _y;
To
midEle.style.left = _x+"px";
midEle.style.top = _y+"px";
Demo: http://jsfiddle.net/muthkum/AFkKt/

Here is a demo if you want to center something in the browser viewport using vanilla JavaScript.
http://jsfiddle.net/CDtGR/5/
<html>
<!--measure size of elements,
get absolute position of elements,
get viewport size and scrollposition-->
<script>
var mesr =
{
Metrics: {
px: 1,
measureUnits: function(target) {
if(typeof(target) == 'undefined')
target = document.getElementsByTagName('body')[0];
mesr.Metrics.measureUnit("em", target);
mesr.Metrics.measureUnit("pt", target);
mesr.Metrics.measureUnit("%", target);
},
measureUnit: function(unit, target) {
if(typeof(target.Metrics) == 'undefined')
target.Metrics = {};
var measureTarget = target;
if(target.tagName == 'IMG' && typeof(target.parentNode) != 'undefined')
measureTarget = target.parentNode;
var measureElement = document.createElement("div");
measureElement.style.width = "1"+unit;
measureElement.style.cssFloat = "left";
measureElement.style.styleFloat = "left";
measureElement.style.margin = "0px";
measureElement.style.padding = "0px";
measureTarget.appendChild(measureElement);
target.Metrics[unit] = measureElement.offsetWidth;
measureElement.parentNode.removeChild(measureElement);
return target.Metrics[unit];
},
getUnitPixels: function(unitString, target) {
if(typeof(target) == 'undefined')
target = document.getElementsByTagName('body')[0];
if(typeof(target.Metrics) == 'undefined')
mesr.Metrics.measureUnits(target);
var unit = unitString.replace(/[0-9\s]+/ig,'').toLowerCase();
var size = Number(unitString.replace(/[^0-9]+/ig,''));
if(typeof(target.Metrics[unit]) == 'undefined')
return 0;
var metricSize = target.Metrics[unit];
var pixels = Math.floor(Number(metricSize * size));
return pixels;
}
},
getElementOffset: function(target) {
var pos = [target.offsetLeft,target.offsetTop];
if(target.offsetParent != null) {
var offsetPos = mesr.getElementOffset(target.offsetParent);
pos = [
pos[0] + offsetPos[0],
pos[1] + offsetPos[1]
];
}
return pos;
},
getElementPosition: function(target) {
var offset = mesr.getElementOffset(target);
var x = offset[0] +
mesr.Metrics.getUnitPixels(target.style.paddingLeft, target) +
mesr.Metrics.getUnitPixels(target.style.borderLeftWidth, target);
var y = offset[1] +
mesr.Metrics.getUnitPixels(target.style.paddingTop, target) +
mesr.Metrics.getUnitPixels(target.style.borderTopWidth, target);
return [x,y];
},
getElementSize: function(target) {
var size = [target.offsetWidth, target.offsetHeight];
size[0] -= mesr.Metrics.getUnitPixels(target.style.paddingLeft, target) +
mesr.Metrics.getUnitPixels(target.style.paddingRight, target) +
mesr.Metrics.getUnitPixels(target.style.borderLeftWidth, target) +
mesr.Metrics.getUnitPixels(target.style.borderRightWidth, target);
size[1] -= mesr.Metrics.getUnitPixels(target.style.paddingTop, target) +
mesr.Metrics.getUnitPixels(target.style.paddingBottom, target) +
mesr.Metrics.getUnitPixels(target.style.borderTopWidth, target) +
mesr.Metrics.getUnitPixels(target.style.borderBottomWidth, target);
return size;
},
getViewPortSize: function () {
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;
}
return [myWidth, myHeight];
},
getViewPortScrollPosition: function () {
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return [ scrOfX, scrOfY ];
},
attachEvent : function(target, eventList, func) {
if(typeof (target) == "undefined" || target == null)
return;
var events = eventList.split(",");
for(var i=0;i<events.length;i++) {
var event = events[i];
if(typeof(target.addEventListener) != 'undefined') {
target.addEventListener(event, func);
} else if(typeof(target.attachEvent) != 'undefined') {
target.attachEvent('on'+event,func);
} else {
console.log("unable to attach event listener");
}
}
}
}
</script>
<!--positioning-->
<script>
function position(){
var viewPortSize = mesr.getViewPortSize();
var viewPortScrollPos = mesr.getViewPortScrollPosition();
var size = mesr.getElementSize(document.getElementById('apa'));
document.getElementById('apa').style.left = Math.floor((viewPortSize[0]/2)-(size[0]/2)+viewPortScrollPos[0])+"px";
document.getElementById('apa').style.top = Math.floor((viewPortSize[1]/2)-(size[1]/2)+viewPortScrollPos[1])+"px";
}
mesr.attachEvent(window,"resize,scroll,load",position);
mesr.attachEvent(document,"load",position);
</script>
<body>
<div id="apa" style="position:absolute;">some text</div>
</body>
</html>

Related

There's an odd infinite scroll on my website after adding some JavaScript to the pages

I've added some JavaScript to my website that adds a glitter effect following the mouse as you move it and I absolutely love it. Except the fact that about halfway down the page a random new scroll bar appears and it scrolls past the footer and on forever. I can't seem to figure out what to add, or take out to make it stop scrolling past the footer. I've tried setting a max height for the body/html... I've tried taking out the "set scroll" function, I need it to stop scrolling on forever. I've also tried adding in the finish() method but I'm not exactly sure where it goes. Here is my code.
var colour = "#ffffff";
var sparkles = 200;
var x = ox = 400;
var y = oy = 300;
var swide = 800;
var shigh = 600;
var sleft = sdown = 0;
var tiny = new Array();
var star = new Array();
var starv = new Array();
var starx = new Array();
var stary = new Array();
var tinyx = new Array();
var tinyy = new Array();
var tinyv = new Array();
colours = new Array('#ffffff', '#cbaa89')
n = 10;
y = 0;
x = 0;
n6 = (document.getElementById && !document.all);
ns = (document.layers);
ie = (document.all);
d = (ns || ie) ? 'document.' : 'document.getElementById("';
a = (ns || n6) ? '' : 'all.';
n6r = (n6) ? '")' : '';
s = (ns) ? '' : '.style';
if (ns) {
for (i = 0; i < n; i++)
document.write('<layer name="dots' + i + '" top=0 left=0 width=' + i / 2 + ' height=' + i / 2 + ' bgcolor=#ff0000></layer>');
}
if (ie)
document.write('<div id="con" style="position:absolute;top:0px;left:0px"><div style="position:relative">');
if (ie || n6) {
for (i = 0; i < n; i++)
document.write('<div id="dots' + i + '" style="position:absolute;top:0px;left:0px;width:' + i / 2 + 'px;height:' + i / 2 + 'px;background:#ff0000;font-size:' + i / 2 + '"></div>');
}
if (ie)
document.write('</div></div>');
(ns || n6) ? window.captureEvents(Event.MOUSEMOVE): 0;
function Mouse(evnt) {
y = (ns || n6) ? evnt.pageY + 4 - window.pageYOffset : event.y + 4;
x = (ns || n6) ? evnt.pageX + 1 : event.x + 1;
}
(ns) ? window.onMouseMove = Mouse: document.onmousemove = Mouse;
function animate() {
o = (ns || n6) ? window.pageYOffset : 0;
if (ie) con.style.top = document.body.scrollTop + 'px';
for (i = 0; i < n; i++) {
var temp1 = eval(d + a + "dots" + i + n6r + s);
randcolours = colours[Math.floor(Math.random() * colours.length)];
(ns) ? temp1.bgColor = randcolours: temp1.background = randcolours;
if (i < n - 1) {
var temp2 = eval(d + a + "dots" + (i + 1) + n6r + s);
temp1.top = parseInt(temp2.top) + 'px';
temp1.left = parseInt(temp2.left) + 'px';
} else {
temp1.top = y + o + 'px';
temp1.left = x + 'px';
}
}
setTimeout("animate()", 10);
}
animate();
window.onload = function() {
if (document.getElementById) {
var i, rats, rlef, rdow;
for (var i = 0; i < sparkles; i++) {
var rats = createDiv(3, 3);
rats.style.visibility = "hidden";
rats.style.zIndex = "999";
document.body.appendChild(tiny[i] = rats);
starv[i] = 0;
tinyv[i] = 0;
var rats = createDiv(5, 5);
rats.style.backgroundColor = "transparent";
rats.style.visibility = "hidden";
rats.style.zIndex = "999";
var rlef = createDiv(1, 5);
var rdow = createDiv(5, 1);
rats.appendChild(rlef);
rats.appendChild(rdow);
rlef.style.top = "2px";
rlef.style.left = "0px";
rdow.style.top = "0px";
rdow.style.left = "2px";
document.body.appendChild(star[i] = rats);
}
set_width();
sparkle();
}
}
function sparkle() {
var c;
if (Math.abs(x - ox) > 1 || Math.abs(y - oy) > 1) {
ox = x;
oy = y;
for (c = 0; c < sparkles; c++)
if (!starv[c]) {
star[c].style.left = (starx[c] = x) + "px";
star[c].style.top = (stary[c] = y + 1) + "px";
star[c].style.clip = "rect(0px, 5px, 5px, 0px)";
star[c].childNodes[0].style.backgroundColor = star[c].childNodes[1].style.backgroundColor = (colour == "random") ? newColour() : colour;
star[c].style.visibility = "visible";
starv[c] = 50;
break;
}
}
for (c = 0; c < sparkles; c++) {
if (starv[c]) update_star(c);
if (tinyv[c]) update_tiny(c);
}
setTimeout("sparkle()", 40);
}
function update_star(i) {
if (--starv[i] == 25) star[i].style.clip = "rect(1px, 4px, 4px, 1px)";
if (starv[i]) {
stary[i] += 1 + Math.random() * 3;
starx[i] += (i % 5 - 2) / 5;
if (stary[i] < shigh + sdown) {
star[i].style.top = stary[i] + "px";
star[i].style.left = starx[i] + "px";
} else {
star[i].style.visibility = "hidden";
starv[i] = 0;
return;
}
} else {
tinyv[i] = 50;
tiny[i].style.top = (tinyy[i] = stary[i]) + "px";
tiny[i].style.left = (tinyx[i] = starx[i]) + "px";
tiny[i].style.width = "2px";
tiny[i].style.height = "2px";
tiny[i].style.backgroundColor = star[i].childNodes[0].style.backgroundColor;
star[i].style.visibility = "hidden";
tiny[i].style.visibility = "visible"
}
}
function update_tiny(i) {
if (--tinyv[i] == 25) {
tiny[i].style.width = "1px";
tiny[i].style.height = "1px";
}
if (tinyv[i]) {
tinyy[i] += 1 + Math.random() * 3;
tinyx[i] += (i % 5 - 2) / 5;
if (tinyy[i] < shigh + sdown) {
tiny[i].style.top = tinyy[i] + "px";
tiny[i].style.left = tinyx[i] + "px";
} else {
tiny[i].style.visibility = "hidden";
tinyv[i] = 0;
return;
}
} else tiny[i].style.visibility = "hidden";
}
document.onmousemove = mouse;
function mouse(e) {
if (e) {
y = e.pageY;
x = e.pageX;
} else {
set_scroll();
y = event.y + sdown;
x = event.x + sleft;
}
}
window.onscroll = set_scroll;
function set_scroll() {
if (typeof(self.pageYOffset) == 'number') {
sdown = self.pageYOffset;
sleft = self.pageXOffset;
} else if (document.body && (document.body.scrollTop || document.body.scrollLeft)) {
sdown = document.body.scrollTop;
sleft = document.body.scrollLeft;
} else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
sleft = document.documentElement.scrollLeft;
sdown = document.documentElement.scrollTop;
} else {
sdown = 0;
sleft = 0;
}
}
window.onresize = set_width;
function set_width() {
var sw_min = 999999;
var sh_min = 999999;
if (document.documentElement && document.documentElement.clientWidth) {
if (document.documentElement.clientWidth > 0) sw_min = document.documentElement.clientWidth;
if (document.documentElement.clientHeight > 0) sh_min = document.documentElement.clientHeight;
}
if (typeof(self.innerWidth) == 'number' && self.innerWidth) {
if (self.innerWidth > 0 && self.innerWidth < sw_min) sw_min = self.innerWidth;
if (self.innerHeight > 0 && self.innerHeight < sh_min) sh_min = self.innerHeight;
}
if (document.body.clientWidth) {
if (document.body.clientWidth > 0 && document.body.clientWidth < sw_min) sw_min = document.body.clientWidth;
if (document.body.clientHeight > 0 && document.body.clientHeight < sh_min) sh_min = document.body.clientHeight;
}
if (sw_min == 999999 || sh_min == 999999) {
sw_min = 800;
sh_min = 600;
}
swide = sw_min;
shigh = sh_min;
}
function createDiv(height, width) {
var div = document.createElement("div");
div.style.position = "absolute";
div.style.height = height + "px";
div.style.width = width + "px";
div.style.overflow = "hidden";
return (div);
}
function newColour() {
var c = new Array();
c[0] = 255;
c[1] = Math.floor(Math.random() * 256);
c[2] = Math.floor(Math.random() * (256 - c[1] / 2));
c.sort(function() {
return (0.5 - Math.random());
});
return ("rgb(" + c[0] + ", " + c[1] + ", " + c[2] + ")");
}
I've also made a jsfiddle here https://jsfiddle.net/5ydty5p2/
it's the sparkles that are wrongly positioned. If you take a look at the inspector (F12 you'll see them animating). The calculated position is incorrected and since they're created directly in the body they make it grow, and grow...
Since the whole script is a hack you could further hack it with a max-height property on the body...
Having sparkless is nice but you should really look for an alternative, this piece of JS is awful. And there is no jquery involved here, it's merely divs following the mouse. You should look for a proper plugin.

Using pure javascript get the element visibility in viewport in percentage

I am trying to get the visibility of the element from viewport in percentage (number %).
Below is the code which I tired, but something is missing.
function calculateVisibilityForDiv(div$) {
var windowHeight = window.innerWidth ||
document.documentElement.clientWidth,
docScroll = window.scrollTop || document.body.scrollTop,
divPosition = div$.offsetTop,
divHeight = div$.offsetHeight || div$.clientHeight,
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll +
windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll +
windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}
return result;
}
}
var getOffset = function(elem) {
var box = { top: 0, left: 0 };
if(typeof elem.getBoundingClientRect !== "undefined") box =
elem.getBoundingClientRect();
return {
x: box.left + (window.pageXOffset || document.scrollLeft || 0) -
(document.clientLeft || 0),
y: box.top + (window.pageYOffset || document.scrollTop || 0) -
(document.clientTop || 0)
};
},
I am trying to get the DOM element visibility percentage from document viewport.
I've modified few lines to work code and it's working fine.
Check below fiddle
https://jsfiddle.net/darjiyogen/q16c1m7s/1/
'use strict';
var results = {};
function display() {
var resultString = '';
$.each(results, function(key) {
resultString += '(' + key + ': ' + Math.round(results[key]) + '%)';
});
$('p').text(resultString);
}
function calculateVisibilityForDiv(div$) {
debugger;
div$ = div$[0];
var windowHeight = window.innerHeight || document.documentElement.clientHeight,
docScroll = window.scrollTop || document.body.scrollTop,
divPosition = div$.offsetTop,
divHeight = div$.offsetHeight || div$.clientHeight,
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll + windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}
return result;
}
}
var getOffset = function(elem) {
var box = {
top: 0,
left: 0
};
if (typeof elem.getBoundingClientRect !== "undefined") box = elem.getBoundingClientRect();
return {
x: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0),
y: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0)
};
};
function calculateAndDisplayForAllDivs() {
$('div').each(function() {
var div$ = $(this);
results[div$.attr('id')] = calculateVisibilityForDiv(div$);
});
display();
}
$(document).scroll(function() {
calculateAndDisplayForAllDivs();
});
$(document).ready(function() {
calculateAndDisplayForAllDivs();
});
div {
height: 300px;
width: 300px;
border-width: 1px;
border-style: solid;
}
p {
position: fixed;
left: 320px;
top: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<p id="result"></p>

Easy Smooth Scroll Plugin: How do I offset scroll?

I am using the Easy Smooth Scroll Plugin for Wordpress.
Below is the .js file that the plugin uses:
var ss = {
fixAllLinks: function() {
var allLinks = document.getElementsByTagName('a');
for (var i = 0; i < allLinks.length; i++) {
var lnk = allLinks[i];
if ((lnk.href && lnk.href.indexOf('#') != -1) && ((lnk.pathname == location.pathname) || ('/' + lnk.pathname == location.pathname)) && (lnk.search == location.search)) {
ss.addEvent(lnk, 'click', ss.smoothScroll);
}
}
},
smoothScroll: function(e) {
if (window.event) {
target = window.event.srcElement;
} else if (e) {
target = e.target;
} else return;
if (target.nodeName.toLowerCase() != 'a') {
target = target.parentNode;
}
if (target.nodeName.toLowerCase() != 'a') return;
anchor = target.hash.substr(1);
var allLinks = document.getElementsByTagName('a');
var destinationLink = null;
for (var i = 0; i < allLinks.length; i++) {
var lnk = allLinks[i];
if (lnk.name && (lnk.name == anchor)) {
destinationLink = lnk;
break;
}
}
if (!destinationLink) destinationLink = document.getElementById(anchor);
if (!destinationLink) return true;
var destx = destinationLink.offsetLeft;
var desty = destinationLink.offsetTop;
var thisNode = destinationLink;
while (thisNode.offsetParent && (thisNode.offsetParent != document.body)) {
thisNode = thisNode.offsetParent;
destx += thisNode.offsetLeft;
desty += thisNode.offsetTop;
}
clearInterval(ss.INTERVAL);
cypos = ss.getCurrentYPos();
ss_stepsize = parseInt((desty - cypos) / ss.STEPS);
ss.INTERVAL = setInterval('ss.scrollWindow(' + ss_stepsize + ',' + desty + ',"' + anchor + '")', 10);
if (window.event) {
window.event.cancelBubble = true;
window.event.returnValue = false;
}
if (e && e.preventDefault && e.stopPropagation) {
e.preventDefault();
e.stopPropagation();
}
},
scrollWindow: function(scramount, dest, anchor) {
wascypos = ss.getCurrentYPos();
isAbove = (wascypos < dest);
window.scrollTo(0, wascypos + scramount);
iscypos = ss.getCurrentYPos();
isAboveNow = (iscypos < dest);
if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
window.scrollTo(0, dest);
clearInterval(ss.INTERVAL);
location.hash = anchor;
}
},
getCurrentYPos: function() {
if (document.body && document.body.scrollTop) return document.body.scrollTop;
if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop;
if (window.pageYOffset) return window.pageYOffset;
return 0;
},
addEvent: function(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent) {
var r = elm.attachEvent("on" + evType, fn);
return r;
} else {
alert("Handler could not be removed");
}
}
}
ss.STEPS = 25;
ss.addEvent(window, "load", ss.fixAllLinks);
The live page is here: http://iamjoepro.com/album/promaha/
I have the smooth scroll scrolling to an anchor, but I would like to offset it by the height of my fixed header (120px)
I am no javascript expert, I'm hoping this is easy for someone, but I can't decipher where to add the offset in my .js file?
I had a similar issue and found that the following solution worked for me.
Change the line:
var desty = destinationLink.offsetTop;
to read:
var desty = destinationLink.offsetTop - 120;
(where '120' is the height in pixels of your fixed header)
Then, remove the line:
location.hash = anchor;
(otherwise, the page will scroll to your 120px offset but then return back to the location of the anchor)
Hope this helps!

How to make this floating menu work only when specific #divs become visible?

I needed to make a floating menu, I searched online and found a script here http://www.jtricks.com/javascript/navigation/floating.html
/* Script by: www.jtricks.com
* Version: 1.12 (20120823)
* Latest version: www.jtricks.com/javascript/navigation/floating.html
*
* License:
* GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*/
var floatingMenu =
{
hasInner: typeof(window.innerWidth) == 'number',
hasElement: typeof(document.documentElement) == 'object'
&& typeof(document.documentElement.clientWidth) == 'number'};
var floatingArray =
[
];
floatingMenu.add = function(obj, options)
{
var name;
var menu;
if (typeof(obj) === "string")
name = obj;
else
menu = obj;
if (options == undefined)
{
floatingArray.push(
{
id: name,
menu: menu,
targetLeft: 0,
targetTop: 0,
distance: .07,
snap: true,
updateParentHeight: false
});
}
else
{
floatingArray.push(
{
id: name,
menu: menu,
targetLeft: options.targetLeft,
targetRight: options.targetRight,
targetTop: options.targetTop,
targetBottom: options.targetBottom,
centerX: options.centerX,
centerY: options.centerY,
prohibitXMovement: options.prohibitXMovement,
prohibitYMovement: options.prohibitYMovement,
distance: options.distance != undefined ? options.distance : .07,
snap: options.snap,
ignoreParentDimensions: options.ignoreParentDimensions,
updateParentHeight:
options.updateParentHeight == undefined
? false
: options.updateParentHeight,
scrollContainer: options.scrollContainer,
scrollContainerId: options.scrollContainerId,
confinementArea: options.confinementArea,
confinementAreaId:
options.confinementArea != undefined
&& options.confinementArea.substring(0, 1) == '#'
? options.confinementArea.substring(1)
: undefined,
confinementAreaClassRegexp:
options.confinementArea != undefined
&& options.confinementArea.substring(0, 1) == '.'
? new RegExp("(^|\\s)" + options.confinementArea.substring(1) + "(\\s|$)")
: undefined
});
}
};
floatingMenu.findSingle = function(item)
{
if (item.id)
item.menu = document.getElementById(item.id);
if (item.scrollContainerId)
item.scrollContainer = document.getElementById(item.scrollContainerId);
};
floatingMenu.move = function (item)
{
if (!item.prohibitXMovement)
{
item.menu.style.left = item.nextX + 'px';
item.menu.style.right = '';
}
if (!item.prohibitYMovement)
{
item.menu.style.top = item.nextY + 'px';
item.menu.style.bottom = '';
}
};
floatingMenu.scrollLeft = function(item)
{
// If floating within scrollable container use it's scrollLeft
if (item.scrollContainer)
return item.scrollContainer.scrollLeft;
var w = window.top;
return this.hasInner
? w.pageXOffset
: this.hasElement
? w.document.documentElement.scrollLeft
: w.document.body.scrollLeft;
};
floatingMenu.scrollTop = function(item)
{
// If floating within scrollable container use it's scrollTop
if (item.scrollContainer)
return item.scrollContainer.scrollTop;
var w = window.top;
return this.hasInner
? w.pageYOffset
: this.hasElement
? w.document.documentElement.scrollTop
: w.document.body.scrollTop;
};
floatingMenu.windowWidth = function()
{
return this.hasElement
? document.documentElement.clientWidth
: document.body.clientWidth;
};
floatingMenu.windowHeight = function()
{
if (floatingMenu.hasElement && floatingMenu.hasInner)
{
// Handle Opera 8 problems
return document.documentElement.clientHeight > window.innerHeight
? window.innerHeight
: document.documentElement.clientHeight
}
else
{
return floatingMenu.hasElement
? document.documentElement.clientHeight
: document.body.clientHeight;
}
};
floatingMenu.documentHeight = function()
{
var innerHeight = this.hasInner
? window.innerHeight
: 0;
var body = document.body,
html = document.documentElement;
return Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight,
innerHeight);
};
floatingMenu.documentWidth = function()
{
var innerWidth = this.hasInner
? window.innerWidth
: 0;
var body = document.body,
html = document.documentElement;
return Math.max(
body.scrollWidth,
body.offsetWidth,
html.clientWidth,
html.scrollWidth,
html.offsetWidth,
innerWidth);
};
floatingMenu.calculateCornerX = function(item)
{
var offsetWidth = item.menu.offsetWidth;
var result = this.scrollLeft(item) - item.parentLeft;
if (item.centerX)
{
result += (this.windowWidth() - offsetWidth)/2;
}
else if (item.targetLeft == undefined)
{
result += this.windowWidth() - item.targetRight - offsetWidth;
}
else
{
result += item.targetLeft;
}
if (document.body != item.menu.parentNode
&& result + offsetWidth >= item.confinedWidthReserve)
{
result = item.confinedWidthReserve - offsetWidth;
}
if (result < 0)
result = 0;
return result;
};
floatingMenu.calculateCornerY = function(item)
{
var offsetHeight = item.menu.offsetHeight;
var result = this.scrollTop(item) - item.parentTop;
if (item.centerY)
{
result += (this.windowHeight() - offsetHeight)/2;
}
else if (item.targetTop === undefined)
{
result += this.windowHeight() - item.targetBottom - offsetHeight;
}
else
{
result += item.targetTop;
}
if (document.body != item.menu.parentNode
&& result + offsetHeight >= item.confinedHeightReserve)
{
result = item.confinedHeightReserve - offsetHeight;
}
if (result < 0)
result = 0;
return result;
};
floatingMenu.isConfinementArea = function(item, area)
{
return item.confinementAreaId != undefined
&& area.id == item.confinementAreaId
|| item.confinementAreaClassRegexp != undefined
&& area.className
&& item.confinementAreaClassRegexp.test(area.className);
};
floatingMenu.computeParent = function(item)
{
if (item.ignoreParentDimensions)
{
item.confinedHeightReserve = this.documentHeight();
item.confinedWidthReserver = this.documentWidth();
item.parentLeft = 0;
item.parentTop = 0;
return;
}
var parentNode = item.menu.parentNode;
var parentOffsets = this.offsets(parentNode, item);
item.parentLeft = parentOffsets.left;
item.parentTop = parentOffsets.top;
item.confinedWidthReserve = parentNode.clientWidth;
// We could have absolutely-positioned DIV wrapped
// inside relatively-positioned. Then parent might not
// have any height. Try to find parent that has
// and try to find whats left of its height for us.
var obj = parentNode;
var objOffsets = this.offsets(obj, item);
if (item.confinementArea == undefined)
{
while (obj.clientHeight + objOffsets.top
< item.menu.scrollHeight + parentOffsets.top
|| item.menu.parentNode == obj
&& item.updateParentHeight
&& obj.clientHeight + objOffsets.top
== item.menu.scrollHeight + parentOffsets.top)
{
obj = obj.parentNode;
objOffsets = this.offsets(obj, item);
}
}
else
{
while (obj.parentNode != undefined
&& !this.isConfinementArea(item, obj))
{
obj = obj.parentNode;
objOffsets = this.offsets(obj, item);
}
}
item.confinedHeightReserve = obj.clientHeight
- (parentOffsets.top - objOffsets.top);
};
floatingMenu.offsets = function(obj, item)
{
var result =
{
left: 0,
top: 0
};
if (obj === item.scrollContainer)
return;
while (obj.offsetParent && obj.offsetParent != item.scrollContainer)
{
result.left += obj.offsetLeft;
result.top += obj.offsetTop;
obj = obj.offsetParent;
}
if (window == window.top)
return result;
// we're IFRAMEd
var iframes = window.top.document.body.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++)
{
if (iframes[i].contentWindow != window)
continue;
obj = iframes[i];
while (obj.offsetParent)
{
result.left += obj.offsetLeft;
result.top += obj.offsetTop;
obj = obj.offsetParent;
}
}
return result;
};
floatingMenu.doFloatSingle = function(item)
{
this.findSingle(item);
if (item.updateParentHeight)
{
item.menu.parentNode.style.minHeight =
item.menu.scrollHeight + 'px';
}
var stepX, stepY;
this.computeParent(item);
var cornerX = this.calculateCornerX(item);
var stepX = (cornerX - item.nextX) * item.distance;
if (Math.abs(stepX) < .5 && item.snap
|| Math.abs(cornerX - item.nextX) <= 1)
{
stepX = cornerX - item.nextX;
}
var cornerY = this.calculateCornerY(item);
var stepY = (cornerY - item.nextY) * item.distance;
if (Math.abs(stepY) < .5 && item.snap
|| Math.abs(cornerY - item.nextY) <= 1)
{
stepY = cornerY - item.nextY;
}
if (Math.abs(stepX) > 0 ||
Math.abs(stepY) > 0)
{
item.nextX += stepX;
item.nextY += stepY;
this.move(item);
}
};
floatingMenu.fixTargets = function()
{
};
floatingMenu.fixTarget = function(item)
{
};
floatingMenu.doFloat = function()
{
this.fixTargets();
for (var i=0; i < floatingArray.length; i++)
{
this.fixTarget(floatingArray[i]);
this.doFloatSingle(floatingArray[i]);
}
setTimeout('floatingMenu.doFloat()', 20);
};
floatingMenu.insertEvent = function(element, event, handler)
{
// W3C
if (element.addEventListener != undefined)
{
element.addEventListener(event, handler, false);
return;
}
var listener = 'on' + event;
// MS
if (element.attachEvent != undefined)
{
element.attachEvent(listener, handler);
return;
}
// Fallback
var oldHandler = element[listener];
element[listener] = function (e)
{
e = (e) ? e : window.event;
var result = handler(e);
return (oldHandler != undefined)
&& (oldHandler(e) == true)
&& (result == true);
};
};
floatingMenu.init = function()
{
floatingMenu.fixTargets();
for (var i=0; i < floatingArray.length; i++)
{
floatingMenu.initSingleMenu(floatingArray[i]);
}
setTimeout('floatingMenu.doFloat()', 100);
};
// Some browsers init scrollbars only after
// full document load.
floatingMenu.initSingleMenu = function(item)
{
this.findSingle(item);
this.computeParent(item);
this.fixTarget(item);
item.nextX = this.calculateCornerX(item);
item.nextY = this.calculateCornerY(item);
this.move(item);
};
floatingMenu.insertEvent(window, 'load', floatingMenu.init);
// Register ourselves as jQuery plugin if jQuery is present
if (typeof(jQuery) !== 'undefined')
{
(function ($)
{
$.fn.addFloating = function(options)
{
return this.each(function()
{
floatingMenu.add(this, options);
});
};
}) (jQuery);
}
The script requires the menu to have #floatdiv id. I made my div, #floatdiv, and added the following line of javascript to the head to make the action start working:
<script type="text/javascript">
floatingMenu.add('floatdiv',
{
targetLeft: 250,
targetTop: 290,
snap: true
});
</script>
the #floatdiv css is here,
#floatdiv{
height:45px;
width:830px;
z-index:2;
}
The script is working fine. When I scroll down, the menu float as specified. But I dun wanna the menu to float all the way with scrolling. I need the float of the menu to fire only when I enter specific divs not all the way with scrolling.. Any clues?
is this what look like?
html
<div id="header">HEADER</div>
<div id="content">
<div id="left">LEFT</div>
<div id="right">RIGHT</div>
</div>
<div id="footer">FOOTER</div>
js
$(function() {
var $sidebar = $("#right"),
$window = $(window),
rightOffset = $sidebar.offset(),
rightDelta = $("#footer").offset().top - $("#header").offset().top - $("#header").outerHeight() - $("#right").outerHeight(),
topPadding = 15;
$window.scroll(function() {
$sidebar.stop().animate({
marginTop: Math.max(Math.min($window.scrollTop() - rightOffset.top + topPadding, rightDelta), 0)
});
});
});
working demo
hope this help you
I wrote the script listed in the question.
The script is very versatile and can make div float within a specific area (e.g. another container div). Here are the instructions:
http://www.jtricks.com/javascript/navigation/floating/confined_demo.html

Trying to find javascript element's position on screen....Not working properly on webkit browsers

This is the code i'm using right now. On webkit browsers (Chrome and Safari Specifically) if the page is scrolled, it doesn't take into account the amount that page has been scrolled. I need help redesigning the function to work for Webkit browsers. And I don't want to be loading up jQuery as this will be used on a web widget and I need to keep the file size down. Thanks guys!
function __getIEVersion() {
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
function __getOperaVersion() {
var rv = 0; // Default value
if (window.opera) {
var sver = window.opera.version();
rv = parseFloat(sver);
}
return rv;
}
var __userAgent = navigator.userAgent;
var __isIE = navigator.appVersion.match(/MSIE/) != null;
var __IEVersion = __getIEVersion();
var __isIENew = __isIE && __IEVersion >= 8;
var __isIEOld = __isIE && !__isIENew;
var __isFireFox = __userAgent.match(/firefox/i) != null;
var __isFireFoxOld = __isFireFox && ((__userAgent.match(/firefox\/2./i) != null) ||
(__userAgent.match(/firefox\/1./i) != null));
var __isFireFoxNew = __isFireFox && !__isFireFoxOld;
var __isWebKit = navigator.appVersion.match(/WebKit/) != null;
var __isChrome = navigator.appVersion.match(/Chrome/) != null;
var __isOpera = window.opera != null;
var __operaVersion = __getOperaVersion();
var __isOperaOld = __isOpera && (__operaVersion < 10);
function __parseBorderWidth(width) {
var res = 0;
if (typeof(width) == "string" && width != null && width != "" ) {
var p = width.indexOf("px");
if (p >= 0) {
res = parseInt(width.substring(0, p));
}
else {
//do not know how to calculate other values
//(such as 0.5em or 0.1cm) correctly now
//so just set the width to 1 pixel
res = 1;
}
}
return res;
}
//returns border width for some element
function __getBorderWidth(element) {
var res = new Object();
res.left = 0; res.top = 0; res.right = 0; res.bottom = 0;
if (window.getComputedStyle) {
//for Firefox
var elStyle = window.getComputedStyle(element, null);
res.left = parseInt(elStyle.borderLeftWidth.slice(0, -2));
res.top = parseInt(elStyle.borderTopWidth.slice(0, -2));
res.right = parseInt(elStyle.borderRightWidth.slice(0, -2));
res.bottom = parseInt(elStyle.borderBottomWidth.slice(0, -2));
}
else {
//for other browsers
res.left = __parseBorderWidth(element.style.borderLeftWidth);
res.top = __parseBorderWidth(element.style.borderTopWidth);
res.right = __parseBorderWidth(element.style.borderRightWidth);
res.bottom = __parseBorderWidth(element.style.borderBottomWidth);
}
return res;
}
//returns the absolute position of some element within document
function getElementAbsolutePos(element) {
var res = new Object();
res.x = 0; res.y = 0;
if (element !== null) {
if (element.getBoundingClientRect) {
var viewportElement = document.documentElement;
var box = element.getBoundingClientRect();
var scrollLeft = viewportElement.scrollLeft;
var scrollTop = viewportElement.scrollTop;
res.x = box.left + scrollLeft;
res.y = box.top + scrollTop;
}
else { //for old browsers
res.x = element.offsetLeft;
res.y = element.offsetTop;
var parentNode = element.parentNode;
var borderWidth = null;
while (offsetParent != null) {
res.x += offsetParent.offsetLeft;
res.y += offsetParent.offsetTop;
var parentTagName =
offsetParent.tagName.toLowerCase();
if ((__isIEOld && parentTagName != "table") ||
((__isFireFoxNew || __isChrome) &&
parentTagName == "td")) {
borderWidth = kGetBorderWidth
(offsetParent);
res.x += borderWidth.left;
res.y += borderWidth.top;
}
if (offsetParent != document.body &&
offsetParent != document.documentElement) {
res.x -= offsetParent.scrollLeft;
res.y -= offsetParent.scrollTop;
}
//next lines are necessary to fix the problem
//with offsetParent
if (!__isIE && !__isOperaOld || __isIENew) {
while (offsetParent != parentNode &&
parentNode !== null) {
res.x -= parentNode.scrollLeft;
res.y -= parentNode.scrollTop;
if (__isFireFoxOld || __isWebKit)
{
borderWidth =
kGetBorderWidth(parentNode);
res.x += borderWidth.left;
res.y += borderWidth.top;
}
parentNode = parentNode.parentNode;
}
}
parentNode = offsetParent.parentNode;
offsetParent = offsetParent.offsetParent;
}
}
}
var scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
scrOfY = document.body.scrollTop;
scrOfX = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
scrOfY = document.documentElement.scrollTop;
scrOfX = document.documentElement.scrollLeft;
}
return res;
}
if (element.getBoundingClientRect) {
var viewportElement = document.documentElement;
var box = element.getBoundingClientRect();
var scrollLeft = viewportElement.scrollLeft;
var scrollTop = viewportElement.scrollTop;
res.x = box.left + scrollLeft;
res.y = box.top + scrollTop;
}
I'm concerned that this code block only uses one way of attempting to detect the scroll position. I would move the bottom block of code to the top of the function and use scrOfX/Y instead of scrollLeft and scrollTop.

Categories

Resources