Monday, 11 October 2021

How can I dynamically change the offset of a Bootstrap 5 dropdown menu using javascript or jQuery?

My web app includes dynamically built Bootstrap 5 dropdown menus that can be quite large. They need to be resized and repositioned to make the best use of screen space. So I'd like to be able to control or adjust the offset computed by Popper.js via javascript. But I haven't been make this work. The Popper.js documentation is not so clear, and I haven't found any documentation or examples of how to do this within Bootstrap 5. (The data-bs-offset attribute isn't suitable since it cannot invoke a function to provide dynamic offset values.)

Please see the code example on JSFiddle https://jsfiddle.net/Martin_ATS/cqw5mjLv/3/. I am able to access the Dropdown object both via bootstrap.Dropdown.getInstance() and via jQuery $(ddelem).dropdown(), as demonstrated in the hideDropdown() function. But I have not been able to change the offset via javascript despite a number of attempts at calling setOptions() etc.

I'd like to use Bootstrap/Popper's computed y offset, but adjust the x offset so that the menu opens closer to the left margin, and ideally leaves a right margin instead of hitting the right side of the window. The code snippet is a simplified example. In the real app, the dropdown menu contents can range from small (for which Bootstrap/Popper's normal offsets work fine) to very large (including horizontal or vertical scrolling).

Thanks!



from How can I dynamically change the offset of a Bootstrap 5 dropdown menu using javascript or jQuery?

No comments:

Post a Comment