I am creating a popover, where I need to position it correctly based on the button's position that triggered it.

It starts like this:

<div id="popoverWrapper" class="popover-wrapper" style={popoverStyle}>
    <section id="popover" class="slds-popover slds-popover_walkthrough slds-popover_large slds-nubbin_left" role="dialog">
        <!--all the insides of the popover-->

I initially just tried a getter on popoverStyle, but when trying to do this.template.querySelector('.popover-wrapper'); it returned null. I thought maybe this was because the getter was happening before actual render.

So I moved the querySelector to the renderedCallback() hook. Putting in a break point, the html is definitely rendered by the time I get to this.template.querySelector('.popover-wrapper'); but it still doesn't find anything.

How might I be able to grab the element in my LWC so I can get its position and dimensions to be able to position properly where I want by finding a space that it will fit?

PS: popoverStyle is getting set to a string that looks like: position: absolute; z-index: 10001; top: ' + correctPositioning.offsetTop + 'px; left: ' + correctPositioning.offsetLeft + 'px;. I am not entirely sure this will even work, but I can't even find the popover element in my JS to try it out.

  • 1
    i tried your code in renderedCallback and it worked. Playgound link – Pranay Jaiswal Mar 15 '19 at 14:58
  • Well, that makes it difficult lol. My component is on a Visualforce page, so I have a lightning component that creates an LWC table with buttons, and those buttons create the LWC popover that is having the issues. I wouldn't think it being nested like that would impact it, especially since I am doing this.template. But yeah, querySelector returned an empty object in my renderedCallback... – Tyler Dahle Mar 15 '19 at 15:08
  • Are you sure there's no other errors loading your component? What does this.template.querySelectorAll("*") return in your components renderedCallback? – TrevorBliss Jun 3 '19 at 20:28
  • Can you try something similar - developer.salesforce.com/docs/component-library/tools/… – Sakthivel Madesh Feb 3 '20 at 0:38

You probably have an error in your component related with the way that you are trying to set the styles, if you remove style={popoverStyle} the this.template.querySelector('.popover-wrapper') must return you the element and there you can set directly using JS, like:

let popup = this.template.querySelector('.popover-wrapper');
popup.style.position = 'absolute'; 
  • Hello @Pirata21, I tried your answer, it doesn't seem to work. I am trying to get the width value of an element in javascript. let mapWidth = this.template.querySelector('.map-root'); console.log(mapWidth.style.width); – sumchans Apr 10 '20 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.