1

Here is part of my code returning a Promise, I am using getBoundingClientRect Async because it runs in AMP virtual DOM (amp-script):

JS:

    button.addEventListener("mouseenter", function(event){
    
       let target = event.target;

       let coords = target.getBoundingClientRectAsync();
       
       console.log(coords);

    });

Console Log:

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
bottom: 366
height: 38
left: 225
right: 352.234375
top: 328
width: 127.234375
x: 328
y: 225
__proto__: Object

How I can get value of left from the object Promise Result? coords.left; returns undefined

la_petite_kozel
  • 826
  • 5
  • 26

1 Answers1

2

If getBoundingClientRectAsync returns a promise, then you can use async / await to get the value.

button.addEventListener("mouseenter", async function(event){
  let target = event.target;
  let coords = await target.getBoundingClientRectAsync();
  console.log(coords.left);
});

Or use the then method of the returned Promise and set a callback where your coords object is made available when the Promise resolves.

button.addEventListener("mouseenter", function(event){
  let target = event.target;
  target.getBoundingClientRectAsync().then(coords => {
    console.log(coords.left);
  });
});

Learn the basics about Promises here on MDN.

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
  • Second solution works! Await solution throws an error telling that it's not an async function for some reason. I will check out the link, much appreciated. – la_petite_kozel May 07 '21 at 11:09
  • Standard amp-html documentation states that Element.getBoundingClientRect() is not supported, see here https://github.com/ampproject/worker-dom/blob/main/web_compat_table.md . However, your provided second example DOES work in amp-html! Thank you for the helpful example! – drumsta Jan 20 '23 at 18:24