How to: Dynamically set <BODY> background-position? - javascript

I posted a question previously that got off topic, I'm reposting with better code that I have VERIFIED is compatible with iPhone (it works with mine anyway!)
I just want to apply background-position coordinates to the body element and call the script conditionally for iPhone, iPod, & iPad. Here's my conditional call for those devices:
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
// do something
} else {
//do this
}
Now, I've found this excellent script that sets the "top: x" dynamically on the basis of scroll position. Everyone has told me (and ALL of the tutorials and Google search results as well) that it's impossible to set scroll position dynamically for iPhone because of the viewport issue. HOWEVER, they are wrong because if you scroll to the bottom of the page and view this javascript demo on iPhone, you can scroll and the
<div style="background-position: fixed; top: x (variable)"></div>
div DOES stay centered on iPhone. I really hope this question helps alot of people, I thought it was impossible, but it's NOT... I just need help stitching it together!
The original code (you can test it on iPhone yourself) is here:
http://stevenbenner.com/2010/04/calculate-page-size-and-view-port-position-in-javascript/
**EDIT: For reference, here is the div that DOES absolute position itself by dynamically applying the "top: x" element as (even on iPhone):
http://stevenbenner.com/2010/04/calculate-page-size-and-view-port-position-in-javascript/**
So I just need help getting the following code to apply the dynamic "background-position: 0 x" to the BODY tag where x is centered and relative to the viewport position. Also, needs to be nested inside the above code that is conditional for iPhone and similar devices.
// Page Size and View Port Dimension Tools
// http://stevenbenner.com/2010/04/calculate-page-size-and-view-port-position-in-javascript/
if (!sb_windowTools) { var sb_windowTools = new Object(); };
sb_windowTools = {
scrollBarPadding: 17, // padding to assume for scroll bars
// EXAMPLE METHODS
// center an element in the viewport
centerElementOnScreen: function(element) {
var pageDimensions = this.updateDimensions();
element.style.top = ((this.pageDimensions.verticalOffset() + this.pageDimensions.windowHeight() / 2) - (this.scrollBarPadding + element.offsetHeight / 2)) + 'px';
element.style.left = ((this.pageDimensions.windowWidth() / 2) - (this.scrollBarPadding + element.offsetWidth / 2)) + 'px';
element.style.position = 'absolute';
},
// INFORMATION GETTERS
// load the page size, view port position and vertical scroll offset
updateDimensions: function() {
this.updatePageSize();
this.updateWindowSize();
this.updateScrollOffset();
},
// load page size information
updatePageSize: function() {
// document dimensions
var viewportWidth, viewportHeight;
if (window.innerHeight && window.scrollMaxY) {
viewportWidth = document.body.scrollWidth;
viewportHeight = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight) {
// all but explorer mac
viewportWidth = document.body.scrollWidth;
viewportHeight = document.body.scrollHeight;
} else {
// explorer mac...would also work in explorer 6 strict, mozilla and safari
viewportWidth = document.body.offsetWidth;
viewportHeight = document.body.offsetHeight;
};
this.pageSize = {
viewportWidth: viewportWidth,
viewportHeight: viewportHeight
};
},
// load window size information
updateWindowSize: function() {
// view port dimensions
var windowWidth, windowHeight;
if (self.innerHeight) {
// all except explorer
windowWidth = self.innerWidth;
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
// explorer 6 strict mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) {
// other explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
};
this.windowSize = {
windowWidth: windowWidth,
windowHeight: windowHeight
};
},
// load scroll offset information
updateScrollOffset: function() {
// viewport vertical scroll offset
var horizontalOffset, verticalOffset;
if (self.pageYOffset) {
horizontalOffset = self.pageXOffset;
verticalOffset = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
// Explorer 6 Strict
horizontalOffset = document.documentElement.scrollLeft;
verticalOffset = document.documentElement.scrollTop;
} else if (document.body) {
// all other Explorers
horizontalOffset = document.body.scrollLeft;
verticalOffset = document.body.scrollTop;
};
this.scrollOffset = {
horizontalOffset: horizontalOffset,
verticalOffset: verticalOffset
};
},
// INFORMATION CONTAINERS
// raw data containers
pageSize: {},
windowSize: {},
scrollOffset: {},
// combined dimensions object with bounding logic
pageDimensions: {
pageWidth: function() {
return sb_windowTools.pageSize.viewportWidth > sb_windowTools.windowSize.windowWidth ?
sb_windowTools.pageSize.viewportWidth :
sb_windowTools.windowSize.windowWidth;
},
pageHeight: function() {
return sb_windowTools.pageSize.viewportHeight > sb_windowTools.windowSize.windowHeight ?
sb_windowTools.pageSize.viewportHeight :
sb_windowTools.windowSize.windowHeight;
},
windowWidth: function() {
return sb_windowTools.windowSize.windowWidth;
},
windowHeight: function() {
return sb_windowTools.windowSize.windowHeight;
},
horizontalOffset: function() {
return sb_windowTools.scrollOffset.horizontalOffset;
},
verticalOffset: function() {
return sb_windowTools.scrollOffset.verticalOffset;
}
}
};

<?php
/* detect Mobile Safari */
$browserAsString = $_SERVER['HTTP_USER_AGENT'];
if (strstr($browserAsString, " AppleWebKit/") && strstr($browserAsString, " Mobile/"))
{
$browserIsMobileSafari = true;
echo
"
<script>
$(document).ready(function() {
$(window).scroll(function() {
windowPosition = $(this).scrollTop();
$('body').stop().animate({'backgroundPositionY' : windowPosition+'px'}, 500);
});
});
</script>
"
;} ?>

Related

manipulate when inview.js is firing

i would like to know how i can manipulate the inview.js script that the moment when its fired is not at first pixels in viewport, and the last when the element is going out but rather for example 50pixels later or earlier.
the script of inview.js is
(function ($) {
function getViewportHeight() {
var height = window.innerHeight; // Safari, Opera
var mode = document.compatMode;
if ( (mode || !$.support.boxModel) ) { // IE, Gecko
height = (mode == 'CSS1Compat') ?
document.documentElement.clientHeight : // Standards
document.body.clientHeight; // Quirks
}
return height;
}
$(window).scroll(function () {
var vpH = getViewportHeight(),
scrolltop = (document.documentElement.scrollTop ?
document.documentElement.scrollTop :
document.body.scrollTop),
elems = [];
// naughty, but this is how it knows which elements to check for
$.each($.cache, function () {
if (this.events && this.events.inview) {
elems.push(this.handle.elem);
}
});
if (elems.length) {
$(elems).each(function () {
var $el = $(this),
top = $el.offset().top,
height = $el.height(),
inview = $el.data('inview') || false;
if (scrolltop > (top + height) || scrolltop + vpH < top) {
if (inview) {
$el.data('inview', false);
$el.trigger('inview', [ false ]);
}
} else if (scrolltop < (top + height)) {
if (!inview) {
$el.data('inview', true);
$el.trigger('inview', [ true ]);
}
}
});
}
});
// kick the event to pick up any elements already in view.
// note however, this only works if the plugin is included after the elements are bound to 'inview'
$(function () {
$(window).scroll();
});
})(jQuery);
all credits go to here
my attemp was to add a value to offset top top = $el.offset().top + 50, which works! but how can i change the value for the bottom up?
thanks ted
I'd recommend using http://imakewebthings.com/jquery-waypoints/
Which you can call like so to achieve your desired effect at 10% from the bottom:
$('.flyIn').waypoint(function() {
$(this).removeClass('hidden');
$(this).addClass('animated fadeInUp');
}, { offset: '90%' });

Javascript: IE Full height

I have the following code to calculate the window width for a lightbox plugin from this site.
* getPageSize() by quirksmode.com
*
* #return Array Return an array with page width, height and window width, height
*/
function ___getPageSize() {
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
return arrayPageSize;
};
I noticed that in Internet Explorer 9, when I click on an image and the Lightbox plugin activates, the transparent back overlay only covers the VIEWABLE height and not the full height.
This creates a problem because, if I have another image with the modified Lightbox plugin and click below the transparent overlay, it opens another empty lightbox window at the top of the page and cannot be closed.
It works fine in Chrome, and Firefox.

Dimensions of containerNode inside dojox dialog widget

I'm trying to get the dimensions of my containerNode which is a member of my dojox dialog widget, when the widget's showing animation ends.
this.dialog = new dojox.widget.Dialog( { sizeToViewport: true });
var dialogContainer = this.dialog.containerNode;
Which function or property should I use?
Since dojo V1.7 you could use dojo.position.
With the given example:
var position = dojo.position(dialogContainer);
var dimensions = {
width: position.w,
height: position.h
}
This call requires dojo/dom-geometry.
Let me know if it worked pls..
Ok, 2nd attempt now. As experimenting a little bit, didn't lead to a solution. How about a nasty little workaround?
Researching on the sizeToViewPort-option of the dojox.widget.dialog i found out, that by default there is a padding of 35px to the ViewPort. So if you know the size of the viewport, you could get the dimensions of the dialog by substracting the padding from it..
So maybe this helps:
function getNewDialog(the_padding) {
if (!the_padding || isNaN(the_padding)) {
the_padding = 35;
}
var dialog = new dojox.widget.Dialog({
sizeToViewport: true,
padding: the_padding + 'px' //nasty string conversion
});
return dialog;
}
function getViewPortSize() {
var viewPortWidth;
var viewPortHeight;
// mozilla/netscape/opera/IE7
if (typeof window.innerWidth != 'undefined') {
viewPortWidth = window.innerWidth;
viewPortHeight = window.innerHeight;
}
// IE6 in standards compliant mode
else if (typeof document.documentElement !== 'undefined' && typeof document.documentElement.clientWidth !== 'undefined' && document.documentElement.clientWidth !== 0) {
viewPortWidth = document.documentElement.clientWidth;
viewPortHeight = document.documentElement.clientHeight;
}
// older versions of IE fallback
else {
viewPortWidth = document.getElementsByTagName('body')[0].clientWidth;
viewPortHeight = document.getElementsByTagName('body')[0].clientHeight;
}
return {
width: viewPortWidth,
heigth: viewPortHeight
};
}
function getDialogSize(the_padding) {
if (!the_padding) {
the_padding = 35;
}
var vp_size = getViewPortSize();
return {
width: vp_size.width - the_padding,
heigth: vp_size.heigth - the_padding
};
}
var costumPadding = 35; // this is also the default value of dojox.widget.dialog ...
var dialog = getNewDialog(costumPadding);
var dialogSize = getDialogSize(costumPadding);
Hope I didn't miss anything.
This is one of possible sollutions
dojo.connect(mydialog, "show", function(){
setTimeout(function(){
var position = dojo.position(dialogContainer);
var dimensions = {
width: position.w,
height: position.h
}
alert(position.h);
},mydialog.duration + 1500);
});

Trigger points for javascript depending on viewport size

So, I'm coding up a site that has certain events triggering as you scroll down the page. I want the events to be triggered when the relevant element hits a point just around a quarter of the way down the viewport.
However, this trigger point is obviously different for different sized viewports. I've worked out how to get this trigger point calculated, but I haven't found a way to get the position of a div relative to the top of the viewport/page.
I am trying to use .offset(), which I could combine with getPageScroll() to find the right point, but I can't figure out what on earth to do with the array that it returns. I've also tried popping it in a variable and using that with the syntax I have below (as used on the jquery.com documentation), but it's patently wrong, and returned Undefined in the console.
I am pretty new to both Javascript and jQuery, and to any actual programming in general, so please excuse any stupidity. If I'm doing this all backwards, that's totally a valid answer too! Please just point me in the correct direction if that's the case.
I've coded it up like this so far. The actual effects are only placeholders for now - I'm just trying to get the basic framework working:
// getPageScroll() by quirksmode.com - adapted to only return yScroll
function getPageScroll() {
var yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
yScroll = document.documentElement.scrollTop;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
}
return yScroll
}
// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
var windowHeight
if (self.innerHeight) { // all except Explorer
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowHeight = document.body.clientHeight;
}
return windowHeight
}
var containers = $('div.container');
var element_1 = $('#part_one');
var element_2 = $('#part_two_1');
var element_3 = $('#part_two_2');
var element_4 = $('#part_two_3');
var element_5 = $('#part_two_4');
var element_6 = $('#part_three');
var element_7 = $('#part_four');
var element_8 = $('#part_five');
var docHeight = $(document).height();
$(window).scroll(function() {
var offset = offset();
var docHeight = $(document).height();
var pageBottom = getPageScroll() + getPageHeight();
var quarterPoint = getPageScroll()+((pageBottom-getPageScroll())/4)
var halfwayPoint = getPageScroll()+((pageBottom-getPageScroll())/2)
var threeQuarterPoint = pageBottom-((pageBottom-getPageScroll())/4)
var triggerPoint = quarterPoint-(getPageHeight/10)
if (triggerPoint < element_1.offset.top){
containers.stop().animate({backgroundColor: "white", color: "#aaa"}, 50);
element_1.stop().animate({backgroundColor: "#ffa531", color: "white"}, 300, function(){
$(this).children().stop().animate({opacity: "1"}, 300);
});
};
if (triggerPoint > element_2.offset.top){
containers.stop().animate({backgroundColor: "white", color: "#aaa"}, 50);
element_2.stop().animate({backgroundColor: "#d900ca", color: "white"}, 300, function(){
$(this).children('img').stop().animate({opacity: "1"}, 300);
});
};
if (triggerPoint > element_3.offset(top)){
containers.stop().animate({backgroundColor: "white", color: "#aaa"}, 50);
element_3.stop().animate({backgroundColor: "#d900ca", color: "white"}, 300);
};
and so on and so forth, for somewhere between 8 and 12 trigger points.
Any help would be greatly appreciated!
Couple things i see here:
var offset = offset(); // i don't believe this is a global function.
if (triggerPoint < element_1.offset.top) { // offset needs to be offset(), its a function not a property

Position a dialog box in center of viewable region of a browser window using javascript/DOM

I need to position a dialog box(read div) in the center of viewable region of a browser window. I need to use javascript DOM for doing this - making use of scrollHeight, scrollTop, clientHeight, etc. is permissible.
The dialog box needs to appear upon clicking a link, it remains invisible otherwise.
CAN'T USE JQUERY TO CREATE A MODAL DIALOG.
Can somebody help me with the centering part of this problem
Regards
(function () {
var getVieportWidth,
getViewportHeight;
if (window.innerWidth) {
// All browsers except IE
getViewportWidth = function() { return window.innerWidth; };
getViewportHeight = function() { return window.innerHeight; };
}
else if (document.documentElement && document.documentElement.clientWidth) {
// IE6 with DOCTYPE
getViewportWidth = function() { return document.documentElement.clientWidth; };
getViewportHeight = function() { return document.documentElement.clientHeight; };
}
else if (document.body.clientWidth) {
// IE4, IE5, IE6 without DOCTYPE
getViewportWidth = function() { return document.body.clientWidth; };
getViewportHeight = function() { return document.body.clientHeight; };
}
var dialogDIVNode = document.getElementById('someID'),
dialogDIVNodeWidth = dialogDIVNode.offsetWidth,
dialogDIVNodeHeight = dialogDIVNode.offsetHeight;
document.getElementById('someLinkID').addEventListener('click', function (e) {
e.preventDefault();
dialogDIVNode.style.left = ( getViewportWidth() / 2 - dialogDIVNodeWidth / 2 ) + 'px';
dialogDIVNode.style.top = ( getViewportHeight() / 2 - dialogDIVNodeHeight / 2) + 'px';
dialogDIVNode.style.display = 'block';
}, false);
}());
Here is how to successfully center a dialog box, regardless of the position in the document:
dialogue.style.left = window.innerWidth - (window.innerWidth - dialogue.offsetWidth) / 2
- dialogue.offsetWidth + pageXOffset;
dialogue.style.top = window.innerHeight - (window.innerHeight - dialogue.offsetHeight) / 2
- dialogue.offsetHeight / 2 + pageYOffset;

Categories