I have a question about positining elements on the screen. When I start my program, it calculates the browser's width and half of the height. I do it only at the beginning. So my horizontal scroller stands at the center, but when I change the browser size during program run, of course it doesn't stand at center. How can I do that?
My calculation of width and height:
function GetWidth()
{
var x = 0;
if (self.innerHeight)
{
x = self.innerWidth;
}
else if (document.documentElement && document.documentElement.clientHeight)
{
x = document.documentElement.clientWidth;
}
else if (document.body)
{
x = document.body.clientWidth;
}
return x;
}
function GetHeight()
{
var y = 0;
if (self.innerHeight)
{
y = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
{
y = document.documentElement.clientHeight;
}
else if (document.body)
{
y = document.body.clientHeight;
}
return y;
}
Hopefuly this will help you: Media Queries CSS
Have a read about these, its what i use to display and control my content between mobiles,tablets and desktops.
Its very hand and easy to use.
use the onresize-event to readjust your gui.
function resize() {
// do something here
}
window.onresize = resize;
Related
I'm still very new to javascript and I'm learning as I build. This may be a simple fix but how would I disable a function on my parallax images ( or disable a specific js function in general ) on a smaller width?
Here's what I have so far that doesn't quite work but shows "undefined". I've been searching for a solution for a couple of days now with no luck. Any help would be appreciated.
var paraLlaxS = document.querySelector("#firstImgc2");
var paraLlaxS = document.querySelector("#secondImgc2");
var paraLlaxS = document.querySelector("#backbox1");
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + ", " + yPos + "px, 0)";
}
window.addEventListener("DOMContentLoaded", scrollLoop, false);
var xScrollPosition;
var yScrollPosition;
function scrollLoop() {
xScrollPosition = window.scrollX;
yScrollPosition = window.scrollY;
setTranslate(0, yScrollPosition * -0.2, firstImgc2);
setTranslate(0, yScrollPosition * 0.15, secondImgc2);
setTranslate(0, yScrollPosition * -0.6, backbox1);
requestAnimationFrame(scrollLoop);
if(window.innerWidth < 900) {
document.querySelector('#firstImgc2').innerHTML = window.removeEventListener("DOMContentLoaded", scrollLoop, false);
return;
} else {
}
}
You could add a conditional return at the beginning of you function. But if the width increases again you would need to listen for that to start the loop again.
function scrollLoop() {
if(window.innerWidth < 900)return;
...
I borrowed a solution from another post.
Listen for browser width for responsive web design?
This code is compatible with a wider variety of browsers as getting the screen size can vary depending on the browser.
var width = 0;
function getWindowSize() {
if (document.body && document.body.offsetWidth) {
width = document.body.offsetWidth;
}
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
width = document.documentElement.offsetWidth;
}
if (window.innerWidth) {
width = window.innerWidth;
}
return(width);
}
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);
});
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jQuery - Check if element is visible after scroling
I'm trying to determine if an element is visible on screen. In order to to this, I'm trying to find the element's vertical position using offsetTop, but the value returned is not correct. In this case, the element is not visible unless you scroll down. But despite of this, offsetTop returns a value of 618 when my screen height is 703, so according to offsetTop the element should be visible.
The code I'm using looks like this:
function posY(obj)
{
var curtop = 0;
if( obj.offsetParent )
{
while(1)
{
curtop += obj.offsetTop;
if( !obj.offsetParent )
{
break;
}
obj = obj.offsetParent;
}
} else if( obj.y )
{
curtop += obj.y;
}
return curtop;
}
Thank you in advance!
--- Shameless plug ---
I have added this function to a library I created
vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------
Intersection Observer
In modern browsers you can use the IntersectionObserver which detects where an element is on the screen or compared to a parent.
The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.
Today I would probably lean toward this API if I need to detect and react to when an element has entered or exited the screen.
But for a quick test/lookup when you just want to verify if an emelemt is currently on screen I would go with the version just below using the getBoundingClientRect.
Using getBoundingClientRect
Short version
This is a lot shorter and should do it as well:
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/
Longer version
And a version with threshold and mode included:
function checkVisible(elm, threshold, mode) {
threshold = threshold || 0;
mode = mode || 'visible';
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
var above = rect.bottom - threshold < 0;
var below = rect.top - viewHeight + threshold >= 0;
return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}
and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/
A more traditional way to do it
As BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.
If you don't use jQuery then the script would be something like this:
function posY(elm) {
var test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
var de = document.documentElement;
if(!!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible( elm ) {
var vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
Using jQuery is a lot easier:
function checkVisible( elm, evalType ) {
evalType = evalType || "visible";
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
if (evalType === "above") return ((y < (vpH + st)));
}
This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.
See in action: http://jsfiddle.net/RJX5N/2/
I hope this answers your question.
Could you use jQuery, since it's cross-browser compatible?
function isOnScreen(element)
{
var curPos = element.offset();
var curTop = curPos.top;
var screenHeight = $(window).height();
return (curTop > screenHeight) ? false : true;
}
And then call the function using something like:
if(isOnScreen($('#myDivId'))) { /* Code here... */ };
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>
"
;} ?>
I have two functions in Javascript:
function getWindowWidth(){
var x = 0;
if (self.innerHeight){
x = self.innerWidth;
}else if (document.documentElement && document.documentElement.clientHeight){
x = document.documentElement.clientWidth;
}else if (document.body){
x = document.body.clientWidth;
}return x;
}function getWindowHeight(){
var y = 0;
if (self.innerHeight){
y = self.innerHeight;
}else if (document.documentElement && document.documentElement.clientHeight){
y = document.documentElement.clientHeight;
}else if (document.body){
y = document.body.clientHeight;
}
These appear to set the height and width of the document window, based on the size of the window? I could be wrong here....
What I have done is embeded a toolbar above this document, this toolbar can be hidden or shown at various points.
I need the above function to be called when I use the following jQuery,
$("#Main").animate({top: "89px"}, 200);
Any assistance greatly appreciated!
animate() takes a callback function.
$("#Main").animate({top: "89px"}, 200, function() {
getWindowWidth();
getWindowHeight(); });