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

212 Views Asked by At

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);
}
2

There are 2 best solutions below

5
Mocca On BEST ANSWER

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!

0
user3632390 On

You can change he ID of this element something else like this

document.querySelector('#window-overlay').id = "somethingelse";

and you did not need to remove the child only change the id of this element remove this line root.removeChild(wo);