Code to hide an element if this element is inside a modal (Updated)

Some pages, in many apps, can be opened in a tab or in a modal, depending of the user journey you created.

For example:

  1. You have one page opening a list details page in the same tab
  2. You have a second page opening the same list details page, but this time in a modal

Some elements (for example a “go back” button) should not appear when the page is opened in a modal.

Here is the code to insert in the page settings => custom code => header

Just change cta1 by the id/name of your block

<script>
window.addEventListener('block-loaded-cta1', () => {
    if (window.self !== window.top) {
        document.getElementById('cta1').style.display = 'none';
    } else {
        document.getElementById('cta1').style.display = 'block';
    }
});
</script>

If you have multiple elements to hide, here is the logic to apply:

<script>
function handleBlockLoaded(elementId) {
    window.addEventListener('block-loaded-' + elementId, () => {
        if (window.self !== window.top) {
            document.getElementById(elementId).style.display = 'none';
        } else {
            document.getElementById(elementId).style.display = 'block';
        }
    });
}

handleBlockLoaded('cta1');
handleBlockLoaded('cta2');
handleBlockLoaded('cta3');
</script>