i have created a virtual numberic keypad by javascript. this keypad position attribute is fixed (or can be absolute) and it's top and left attributes have determind in css. when user focuses a text input, (by a function that fires by "onfocus" event) the key pad appears in page and the user can type numbers in the focused input (like secure virtual keypads in Banks payment gateways but numbers place of my keypad aren't as random). my keypad container tag css codes is as following codes:
#numPadContainer {
display: none; /* Hidden by default */
position: absolute; /* Stay in place */
z-index: 1; /* Sit on top */
right: 1000px;
top: 260px;
text-align: center;
}
with this css code the place of keypad is same for all of inputs. but i like my virtual key pad appears under the focused input. for this issue i need to get the place of focused input in javascript (the top and right attribiutes of focuased input) then change them. but following js code doesn't return these atributes. (my inputs position attribute is static)
let x=document.getElementByID("firstInput").style.right;
let y=document.getElementByID("firstInput").style.top;
can you present me a js method to get x and y attribute of focuased input or another way to appear my virtual keypad under the focused text input?
CodePudding user response:
const elem = document.getElementByID("firstInput")
const { top, right, left, bottom } = elem.getBoundingClientRect();
Tip: Always use
const
when declaring variables, change it tolet
only when you have to reassign the value
You can't rely on style to give you the actual value cos styles are declared rules, they don't change if the position of the elements changes on the page (with JS).
getBoundingClientRect returns the actual position of the element.