Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to find the distance between the element and the bottom of the browser window

Tags:

jquery

I need to find the distance between the element and the bottom of the browser window.

When I select the element, and the distance between the element and the bottom of the browser window is smaller than 50px, I want to make the window scroll automatically.

Any ideas? I'd prefer to use jQuery.

like image 838
diogorighi Avatar asked Oct 05 '11 02:10

diogorighi


People also ask

How far is the element from the top of the window?

You can use . offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled: var scrollTop = $(window).

How do you get the distance from the top for an element?

To get the distance from the top for an element with JavaScript, we get the sum of the window. pageYOffset property and the element's top value. const elDistanceToTop = window. pageYOffset + el.


1 Answers

Unlike other systems coordinates in browser is from top to bottom, it means top of the browser is y=0.

There is two DOM element property for getting position of an element on the page. The properties are element.offsetTop and element.offsetHeight

You can calculate the space between your element and bottom of the page by calculating element.offsetTop and window.innerHeight.

var space = window.innerHeight - element.offsetTop 

if you want to calculate space between bottom of your element and bottom of the window then you need to add your element height too.

var space = window.innerHeight - element.offsetTop + element.offsetHeight 

This calculation is sometimes necessary. Think you have percent based positioning and you want to know position of your element by pixels to do something. For example you have a div positioned like this:

div{     width:300px;     height:16.2%;     position:absolute;     top: 48.11%;     border:3px dotted black; } 

Then you want to know when the div is close to browser window to change it's color:

var div = document.querySelector('div'),     space = innerHeight - div.offsetTop + div.offsetHeight;   window.onresize = function(){     space = innerHeight - div.offsetTop + div.offsetHeight;     if(space < 200){         div.style.background = 'blue';     } }; 

Fiddle

like image 108
Mohsen Avatar answered Sep 19 '22 15:09

Mohsen