get position of element javascript code example
Example 1: javascript get scroll position
function getYPosition(){
var top = window.pageYOffset || document.documentElement.scrollTop
return top;
}
Example 2: get mouse position javascript
<p>Click in the div element below to get the x (horizontal) and y (vertical) coordinates of the mouse pointer, when it is clicked.</p>
<div onclick="showCoords(event)"><p id="demo"></p></div>
<p><strong>Tip:</strong> Try to click different places in the div.</p>
<script>
function showCoords(event) {
var cX = event.clientX;
var sX = event.screenX;
var cY = event.clientY;
var sY = event.screenY;
var coords1 = "client - X: " + cX + ", Y coords: " + cY;
var coords2 = "screen - X: " + sX + ", Y coords: " + sY;
document.getElementById("demo").innerHTML = coords1 + "<br>" + coords2;
}
</script>
Example 3: javascript get element position relative to document
element.getBoundingClientRect().top + document.documentElement.scrollTop
Example 4: js get element by X Y
// get the element at a certain (x, y) position
var element = document.elementFromPoint(x, y);
// for a list of elements
var elements = document.elementsFromPoint(x, y);
.
Example 5: how to show a certain position in javascript
//How to print a specific element in javascript
/*====DESCRIPTION starts here=====
You can output a specific element or position of a list/array by
using the output statement which is console.log(). Within it, type in the
name of the array in which you are dealing with, and specify with brackets
after the array name, enter the number of the
position you want to output. Note though that as computers
count beginning from 0, you will have to subtract
1 from the original position we percieve.
====DESRCIPTION ends here=======*/
//====EXAMPLE 1 STARTS HERE=========
//Using an integer to output a specific element/position of an array.
//array named "arr" which consists of 4 elements which are integers.
var arr = [3,4,5,2]
console.log(arr[2]) //Outputs "5" because 5 is the second (or third) element of the array.
//====EXAMPLE 1 ENDS HERE=========
//====EXAMPLE 2 STARTS==========
//Using a variable to output a specific element/position of an array.
//array named "arr" which consists of 4 elements which are integers.
var arr = [8,9,3,5]
//A variable named "i" which stores a value of an integer, 2.
//Will be used to output the second element of the array.
var x = 0
console.log(arr[x]) //Outputs "8" since 8 is the 0 (or first) elemnt of the arary.
//====EXAMPLE 2 ENDS HERE==========