div element position in screen 1

div element position in screen

function offset(el) {    var rect = el.getBoundingClientRect(),    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,    scrollTop = window.pageYOffset || document.documentElement.scrollTop;    return { top: rect.top + scrollTop, left: rect.left + scrollLeft }}
// example usevar div = document.querySelector('div');var divOffset = offset(div);console.log(divOffset.left, divOffset.top);

Here is what the above code is Doing:
1. We create a function called offset that takes an element as a parameter.
2. We create a variable called rect that stores the element’s position using the getBoundingClientRect() method.
3. We create two variables called scrollLeft and scrollTop that store the amount of pixels the document is scrolled horizontally and vertically.
4. We return an object with the top and left positions of the element.
5. We create a variable called div that stores a reference to the div element.
6. We create a variable called divOffset that stores the top and left positions of the div element.
7. We log the top and left positions of the div element to the console.

Similar Posts