Problem Statement
When a widget is added to a page and hidden using display: none; in the CSS, it can interfere with the layout of the page. The class for the smallest screen size will take effect, potentially causing positioning issues for other elements.
Solution 1: Keeping space
The visibility
CSS property allows you to show or hide an element without altering the layout of a document. When an element's visibility is set to hidden
, it remains in the layout, occupying the space it would normally take up.
As a result, the layout of the document will always remain consistent regardless of whether an element's visibility is set to hidden
or visible
.
<!-- Set CSS style to element you are loading widget into -->
<div id="widget" class="sr-widget" style="visibility: hidden"></div>
<script>
const widget = document.getElementById('widget');
// Change widget visibility
const onWidgetToggle = () => {
widget.style.visibility = widget.style.visibility === 'hidden' ? 'visible' : 'hidden';
}
</script>
Solution 2: Without Taking Space
When you want the widget to remain hidden without occupying space on the page, use the display
CSS property with the value none
. However, it's important to note that when transitioning from display: none
to a visible state, you will need to trigger a resize event to ensure that the layout is repositioned and the sizes of elements are recalculated.
<!-- Set CSS style to element you are loading widget into -->
<div id="widget" class="sr-widget" style="display: none;"></div>
<script>
const widget = document.getElementById('widget');
// Change widget visibility
const onWidgetToggle = () => {
// First change display from none
widget.style.display = widget.style.display === 'none' ? 'block' : 'none'
// Then trigger resize event
window.dispatchEvent(new Event('resize'));
}
</script>