2

I want to get the width of an element in js and based on that width want to perform some animations. I am resizing the width of the below div from 1112px to 752px through CSS animation, when it reaches 752px I want animation on another element to begin.

HTML
<div id="mapId" class="map-root" lwc:dom="manual"></div>

CSS
.map-root {
    height: 370px;
    width: 1112px;
    border-radius: 5px;
}

.map-root-animation {
    animation: mapWidthAnimation 0.5s forwards 0s ease;
}

@keyframes mapWidthAnimation {
    0% {
        width: 1112px;
        height: 370px;
    }

    100% {
        width: 752px;
        height: 370px;

    }
}

On the click event of a button:

this.template.querySelector('.map-root').classList.add('map-root-animation');
let mapWidth = this.template.querySelector('.map-root');
console.log(mapWidth.style.width);// I get blank value in the console.
if (mapWidth.style.width == 752px) { //do something }

1 Answer 1

6

The style attribute tells you what the style was set to. To get the actual current size, use getBoundingClientRect():

console.log(mapWidth.getBoundingClientRect().width);

Note that this will be an actual number, not a string. For example, it'll be equal to 752, not 752px).

However, what you're probably looking for is to watch for the end of the animation:

mapWidth.addEventListener('animationend', this.handleAnimationEnd.bind(this));
4
  • Thanks again @sfdcfox Commented Apr 10, 2020 at 20:11
  • Thanks @sfdcfox ! getBoundingClientRect() is indeed the ticket. Thing is the querySelector result is quite inscrutable in debug because of the Proxy() that the aura_prod.js hides it behind. Is there some reference page which documents the members/methods that we can expect to "reach" through the Proxy which Aura imposes over the HTML elements? Commented Dec 10, 2020 at 21:55
  • @BorisGaspic You can check the Locker API Viewer for methods and attributes you'll have access to. Commented Dec 10, 2020 at 21:58
  • @sfdcfox great reference, thank you for the link! I wasn't aware of that page Commented Dec 12, 2020 at 16:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.