Search code examples
javascriptremovechildclonenode

RemoveChild when onclick() only on parent (outside of element)


How to avoid closeWindow() call on #window? Currently #window-overlay is removed with all nested childs when clicked anywhere on screen. But i want to do this only when clicked on #window-overlay and not to #window. So #window could have its own click events. I am absolute noob in JS. Just trying to do modal kind stuff without using display:block, etc... Idea is simple, no matter what, my window always will be on top of everything else as it is appended to document.body and i don't need to care much about z-index collisions and other stuff. As well, cloneNode is pretty performant. I know, my functions are not reusable, but i will deal with this later. Probably i need to deal with e.stopPropagation() but not sure how to implement this.

<template id="my-test">
    <div id="window-overlay" class="my-test" onclick="closeWindow()">
        <div id="window" class="window">
            <p>My Window</p>
        </div>
    </div>
</template>

function openProfile() {
    var myTest = document.querySelector('#my-test').content;
    document.body.appendChild(myTest.cloneNode(true));
}

function closeWindow() {
    var wo = document.querySelector('#window-overlay');
    var root = document.body
    root.removeChild(wo);
}

Solution

  • The click action is being propagated from your #window component through your #window-overlay.

    Then, you need to stop this propagation, and you can do it this way

    <template id="my-test">
        <div id="window-overlay" class="my-test" onclick="closeWindow()">
            <div id="window" class="window" onclick="e => e.stopPropagation()">
                <p>My Window</p>
            </div>
        </div>
    </template>
    

    If you need to do other things when clicking in your #window component, then you could define its own function, for example

    <template id="my-test">
        <div id="window-overlay" class="my-test" onclick="closeWindow()">
            <div id="window" class="window" onclick="foo(event)">
                <p>My Window</p>
            </div>
        </div>
    </template>
    
    
    function foo(e) {
         e.stopPropagation();
    
         // your stuff here ...
    }
    

    Hope it helps!