Problem:
Codepen: https://codepen.io/vvaciej/pen/abPdEBN
Don’t know how to do a function that closes a menu when active by right click outside
const menuButton = document.querySelector('.fa-bars');
const barsArea = document.querySelector('.bars-area');
const bodyArea = document.querySelector('body');
menuButton.addEventListener('click', function () {
if (!barsArea.classList.contains('active')) {
barsArea.classList.add('active');
} else if (barsArea.classList.contains('active')) {
barsArea.classList.remove('active');
}
});
I tried this:
bodyArea.addEventListener('click', function() {
if (barsArea.classList.contains('active') {
barsArea.classList.remove('active');
{
});
But it didn’t work. So I ask you guys maybe somebody knows how to do it right!!!??
Solution:
You have to change bodyArea.addEventListener
to document.addEventListener
. Starting with barsArea.classList.contains('active')
is a good beginning, and barsArea
does not have a target !barsArea.contains(e.target)
and the target has not to be a menuButton
. so that you can remove the active one like you did barsArea.classList.remove('active');
:
document.addEventListener('click', function (e) {
if (barsArea.classList.contains('active') &&
!barsArea.contains(e.target) &&
e.target !== menuButton) {
barsArea.classList.remove('active');
}
});