get element position javascript code example
Example 1: get caret position javascript
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
Example 2: 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 3: Get the position of a div/span tag
function getPos(el) {
// yay readability
for (var lx=0, ly=0;
el != null;
lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x: lx,y: ly};
}
Example 4: 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==========