Calculate what portion of div is off the screen - javascript

I have a div that is position: absolute. Sometimes on smaller screen resolutions it goes off the screen. Is it possible to calculate in px how much of it is off the screen?

As has been already mentioned, this really isn't the way for solving this problem, however the code you need is:
const offsetRight = document.querySelector('.your-element').getBoundingClientRect().right - window.innerWidth
This code gets the px value of the right edge of your element and calculates the difference between that and the edge of the window.
For the left side:
const offsetLeft = 0 - document.querySelector('.your-element').getBoundingClientRect().left;

Related

Detecting VH on mobile in js and returning it's current value

My issue is a hack for a dubious mobile browser discrepancy between the 100vh and the area hidden behind the mobile browser bars. This is a problem for any page where a full screen effect is desired.
The hack detects the difference between the VH and the actual visible viewport. However the simple js in the first code example appears to be detecting it backwards. So if the browser bar is overlaid the value should be 75 but is instead 0 -- likewise when the the browser is large it should return 0 but instead returns -75.
This can be reproduced simply by testing an iPhone with the 'develop' tool in Safari on google.com and entering this in the console.
document.documentElement.clientHeight - window.innerHeight
This seems to compute the shorter browser height with the top offset to compensate for the browser bar as being offset by 0 and the tall browser height where the browser bar is no longer covering the top of the page at -75px. This, to me, appears to be very wrong and should be 75 and 0 respectively. The below example is how I think it should work to properly offset the body tag to position elements with absolute positioning.
function fixIt(){
var offset = (document.documentElement.clientHeight - window.innerHeight);
document.body.style.marginTop = offset;
}
fixIt(); // run on resize
My extra super hacky solution it to offset the body by 75px by default and to assign the old value on vertical resize. (so when the browser bars hide, instead of 75px offset, use previous offset of 0 and save the 75px offset for the next resize). The works in Mobile Chrome and Mobile Safari, but for instance, if the link is opened in facebook where there is no browser bar and no resize events, it is offset by 75px permanently. This code is obviously insane and should be banished into the nothing.
var offset;
var oldOffset = 75px;
function fixIt(oldOffset){
offset = (document.documentElement.clientHeight - window.innerHeight);
document.body.style.marginTop = oldOffset;
oldOffset = offset;
return oldOffset;
}
fixIt(oldOffset); // run on resize
As an aside, or for further reading, here's a big complaint blog on the issue. https://nicolas-hoizey.com/2015/02/viewport-height-is-taller-than-the-visible-part-of-the-document-in-some-mobile-browsers.html I agree with the browser vendors that VH should be constant (because the reflow would be obnoxious for everything besides the actual body height) but for the top level elements like body and html tags on mobile this behavior appears to be wrong and it makes no semantic sense, plus these computed numbers appear backwards, further making this issue headache inducing.
What other solutions are out there?

Get the max-viewport size of user browser window

I am working on a project including several draggable divs using jQuery-UI with the constrain functionality to help the user avoid stray divs hiding in the outskirts.
Now I am getting the full screen dimensions for the constrains:
var width = window.screen.availWidth;
var height = window.screen.availHeight;
And that is pretty close to what I desire. However, as all browser have the tabs and search input line on the top and often some other stuff at the bottom I am getting a bigger constrain than the actual view port. Then you say get the view port dimensions:
$(window).height();
$(window).width();
Well, that is close to but it is not 100%, because if the user has a minimized window when entering the site that view port size is going to be the constrain size. This means that if the user then uses full screen the constraint is just as big as the view port were from the start.
Then you might say: "Why not change the constrain dynamically along the way?"
Well, that could have been a possibility but this whole page idea is to fine tune the GUI and by changing the constrain size could potentially mess upp the positioning of the draggable objects. So, what am I asking for?
I am asking for a way to get the maximum browser view port size on the current users screen? No matter if the user has a smaller than max browser window ATM when entering the page.
PS. I suppose I could check which browser the user is using and by hard code remove the amount of pixels that specific browsers head-bar is using. That however is a bad solution in my book, for several reasons.
with some good suggestions pointing me in the right direction I have now understood my problem.. I think.
These two bad boys are actually doing the trick:
var width = window.screen.availWidth;
var height = window.screen.availHeight;
BUT!! I am on a desktop running windows and the taskbar at the bottom is actually overlaying the chrome browser window! This was what made me confused to start with. So... yeah. I guess that is it. I just have to live with my users beeing able to put the divs under the win taskbar. Well ok! Bye
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
Although pretty hacky, you could take advantage of the viewport units of css.
$('body').css({
'height': '100vh',
'width': '100vw'
});
var height = $('body').height(); // or innerHeight or OuterHeight
var width = $('body').width();
vw : Relative to 1% of the width of the viewport
vh : Relative to 1% of the height of the viewport
vmin : Relative to 1% of viewport's smaller dimension
vmax : Relative to 1% of viewport's larger dimension
https://www.w3schools.com/cssref/css_units.asp
You can use $(window).outerWidth() and $(window).outerHeight()
You may refer these links.
https://developer.mozilla.org/en-US/docs/Web/API/Window/outerHeight
https://developer.mozilla.org/en-US/docs/Web/API/Window/outerWidth

How do I move the background image of a DIV based on the scrollbar movement?

I have been looking into parallax effects for vertical scrolling on my web page, and after some research, I'm not sure that what I want to do is technically a parallax effect.
From what I've seen, most parallax effects assume you want to be able to scroll indefinitely with many background images rolling by, or with huge images that repeat.
What I want to do is have the background of two DIVs be filled with a background image as the scroll bar reaches the bottom of the page. Note that I do not want the background images to stretch. I'm assuming to get the effect I want that these images would have a vertical height bigger than most people's viewport, and then their vertical position would change. When the user's scrollbar is at the top, a certain amount of the background is visible, and then it moves vertically to fill the background space as the user scrolls down.
Please see the image below for a visual explanation of the effect I hope to acheive:
The height of the veiwport will vary depending on the length of content inside the inner DIV.
My trouble is that if what I am trying to do is not exactly a parallax effect, then I don't know what else to call it, and my attempts to search by describing it keep landing me back at pages offering tutorials on parallax effects. So I've been stumped by a lack of terminology.
If someone could direct me to how I can control the vertical position of the background depending on the scrollbar position, that would be much appreciated. If this can be done with just CSS that would be great, but I'm assuming some Javascript would be required. A jQuery solution would also work for me.
Update:
After searching using the terms provided in comments, I've got the background image in the outer DIV to almost do what I want with the following code:
$(window).scroll(function () {
var yPos = $("#outerDiv").height() - ($("#outerDIV").height() * ($(window).scrollTop() / $(window).height()));
document.getElementById('outerDIV').style.backgroundPosition="0px " + yPos + "px";
});
It moves the background image in the right direction relative to the scrolling, but what it lacks is constraining that motion to within the viewport. Getting the right proportions based on the viewport and DIV sizes is proving to be just a little beyond my mathematical abilities.
For your requirement, you have to use a jquery parallax plugin to guide this activity, my best suggest it to use a Superscollorama and play with the elements as your wish...
As far as your question, Try this example,
controller.addTween(
'#examples-background',
(new TimelineLite())
.append([
TweenMax.fromTo($('#parallax-it-left'), 1,
{css:{backgroundPosition:"(0 -54px)"}, immediateRender:true},
{css:{backgroundPosition:"(0 -54px)"}}),
TweenMax.fromTo($('#parallax-it-right'), 1,
{css:{backgroundPosition:"(0 -54px)"}, immediateRender:true},
{css:{backgroundPosition:"(0 54px)"}})
]),
1000 // scroll duration of tween
);
You serial vice change as far as your wish...
Try practice this plugin, hope that works for you...
http://johnpolacek.github.io/superscrollorama/
Thanks...
Turns out what I want to acheive is possible with no special plugins, just some carefully thought out math. I did use a little jQuery syntax, but I don't think it's strictly necessary.
The code below has copious notes, so hopefully it's largely explanatory. In summary, you just need to find the position of the background image when the scroll would be at the top, and the position it would be if the scroll bar was at the bottom, and then you can use the percentage of the scrollbar's movement to work out where you are between those two points. It's a little tricker than just that, of course, in that you have to account for the difference between the total height of the scroll bar and where your DIV appears on the page and a few other adjustments, but the details of what I did are below.
What I've done here is just for the "outer DIV" that I described in my question. To get a background to move like the "inner DIV" I described, you'd have to modify the code, presumeably by reversing a few parameters. I haven't done that yet, but it seems like a straightforward task.
Hope others find this code useful. If anyone has suggestions on how it can be made more efficient or better, please let me know.
function moveBG(){
// imageHeight is not the total height of the image,
// it's the vertical amount you want to ensure remains visible no matter what.
var imageHeight = 300;
// Get the maximum amount within the DIV that the BG can move vertically.
var maxYPos = $("#outerDIV").height() - imageHeight;
// Get the amount of vertical distance from the top of the document to
// to the top of the DIV.
var headerHeight = document.getElementById("outerDIV").offsetTop;
// Calculate the BG Y position for when the scrollbar is at the very top.
var bgTopPos = $(window).height() - headerHeight - imageHeight;
// I don't want the image to wander outside of the DIV, so ensure it never
// goes below zero.
if (bgTopPos < 0)
{
bgTopPos = 0;
}
// Calculate the BG Y position when the scrollbar is at the very top.
var bgBottomPos = $(document).height() - $(window).height() - headerHeight;
// To prevent the BG image from getting cut off at the top, make sure
// its position never exceeds the maximum distance from the top of the DIV.
if (bgBottomPos > maxYPos)
{
bgBottomPos = maxYPos;
}
// Subtract the top position from the bottom, and you have the spread
// the BG will travel.
var totalYSpan = bgBottomPos - bgTopPos;
// Get the scrollbar position as a "percentage". Note I simply left it as a
// value between 0 and 1 instead of converting to a "true" percentage between
// 0 and 100, 'cause we don't need that in this situation.
var scrollPercent = ($(window).scrollTop() / ( $(document).height() - $(window).height()));
// The percentage of spread is added to the top position, and voila!
// You have your Y position for the BG image.
var bgYPos = bgTopPos + (Math.round(totalYSpan * scrollPercent));
// Apply it to the DIV.
document.getElementById('outerDIV').style.backgroundPosition="0px " + bgYPos + "px";
}
// Place the BG image correctly when opening the page.
$(document).ready(function() {
moveBG();
});
// Make it update when the scrollbar moves.
$(window).scroll(function () {
moveBG();
});

Parallax relative to a background's current position

I'm attempting to create a parallax effect (which works great) however there is a small problem. Instead of the parallax being relative from the element's current position, it jumps to 0. How would I be able to have the parallax affect it's position relative to it's current position?
Here is my javascript:
$("#caveConfron").mousemove(function(e){
var x = e.pageX - this.offsetLeft;
var alreadyY = $("#caveConfron").css("backgroundPositionY");
$("#caveConfron").css({"backgroundPosition":-(x/85)+"% 0%"});
});
And my CSS for the element:
#caveConfron{
width:242px;
height:344px;
border:5px solid black;
background:url('../img/caveConfrontBg.jpg') no-repeat center top;
position:relative;
}
Here is an example of what happens: http://jsfiddle.net/gNCjS/
After much experimentation, I figured out the problem.
First and foremost, when the mouse hits the center of the div, the value of the mouse position of x should be "0". So this is what I did without tweaking the CSS:
$("#caveConfron").mousemove(function(e){
var x = e.pageX - this.offsetLeft;
var reduce = $(this).width()/2;
$("#caveConfron").css({"backgroundPosition":(((-x+reduce)/55)+50)+"% 0%"});
});
The variable reduce gets half of the width of the div. Then, I get the negative of the variable x while adding it to the the value of reduce so if the mouse position of x surpasses half of the div, it will go positive, so the middle will perpetually be "0." I then divide 55 so it wont jump sporadically when moving around on the x axis, it will be a small change (feel free to tweak this value if you want the jump to be much more substantial; for my purposes it was great). On top of that, I add 50, because in my original CSS the background's position is centered which coincidentally puts the value (in number terms) at 50%.
Hope my explanation was good!

Browser relative positioning with jQuery and CutyCapt

I've been using CutyCapt to take screen shots of several web pages with great success. My challenge now is to paint a few dots on those screen shots that represent where a user clicked.
CutyCapt goes through a process of resizing the web page to the scroll width before taking a screen shot. That's extremely useful because you only get content and not much (if any) of the page's background.
My challenge is trying to map a user's mouse X coordinates to the screen shot. Obviously users have different screen resolutions and have their browser window open to different sizes. The image below shows 3 examples with the same logo. Assume, for example, that the logo is 10 pixels to the left edge of the "content" area (in red).
In each of these cases, and for any resolution, I need a JavaScript routine that will calculate that the logo's X coordinate is 10. Again, the challenge (I think) is differing resolutions. In the center-aligned examples, the logo's position, as measured from the left edge of the browser (in black), differs with changing browser size. The left-aligned example should be simple as the logo never moves as the screen resizes.
Can anyone think of a way to calculate the scrollable width of a page? In other words, I'm looking for a JavaScript solution to calculate the minimum width of the browser window before a horizontal scroll bar shows up. And I need to do this without first knowing any element IDs or class names.
Thanks for your help!
You can get the total space an element needs:
function getWidth(x){
var totalWidth = x.width();
totalWidth += parseInt(x.css("padding-left"), 10) + parseInt(x.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(x.css("margin-left"), 10) + parseInt(x.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(x.css("borderLeftWidth"), 10) + parseInt(x.css("borderRightWidth"), 10); //Total Border Width
return totalWidth;
}
You have to add that to the position of the element:
$('#yourlogo').offset().left;
So:
var window-width = $('#yourlogo').offset().left + getWidth($('#yourlogo'));
Hope this helps :-??
If I understand you correctly, then this is what should work for you!
var browserWidth=$(window).width(); // returns width of browser viewport
It should return the width of the persons browser window.
Hope this helps!

Categories