I want to make a "popup" box activated by a button that reduces the opacity of all other elements. When the user clicks out of the box, it should disappear and the opacity should go back to normal. However, these two functions are conflicting with each other. It requires me to click the button TWICE in order for showBox()
to be called. And clicking out of the box does nothing unless I reinvoke hideOnClickOutside(document.querySelector('div'));
in the browser's console.
Why do I have to click "New Audio" twice and why does hideOnClickOutside()
not work unless reinvoked?
function showBox() {
document.body.style.opacity = "0.5";
document.querySelector('div').style.display = "block";
}
document.querySelector('button').addEventListener('click', showBox);
const isVisible = elem => !!elem && !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
element.style.display = 'none';
removeClickListener()
document.body.style.opacity = "1";
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
hideOnClickOutside(document.querySelector('div'));
<button>New Audio</button>
<div style="display: none">
<button>Record Directly</button>
</div>
hideOnClickOutside()
function was taken from another StackOverflow answer
Edit
I figured out that it requires two clicks because on the first click, showBox()
is called, but immediately after, so is outsideClickListener, and at this point the element is NOW visible AND the user has clicked "outside" the element. This reverts the style changes of showBox()
.