user11219078
user11219078

Reputation:

Why is my class not being toggled by this JavaScript function?

I am trying to toggle .active class when clicked on the #datePickerStart div. It only toggles when i click on the div but I want the element to be hidden when clicked outside of datepicker.

$('#datePickerStart').addEventListener('click', (e) => {
    console.log(e.path);
    if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
        $('#dropDownStart').classList.toggle('active');
    }
});

function checkEventPathForClass(path, selector) {
    for (item of path) {
        if (item.classList && item.classList.contains(selector)) {
            return true;
        }
    }
    return false;
}
.active {
    display: block;
}

JSBin for my website.

Upvotes: 0

Views: 93

Answers (3)

brk
brk

Reputation: 50316

Create a separate function like shouldToggleClass and call that function from both the event listener. Also you can directly use the click instead of addEventlistener since jquery is already used

const $ = (selector) => {
  return document.querySelector(selector);
};

$('#datePickerStart').addEventListener('click',(e) => {
  shouldToggleClass(e)

});

function shouldToggleClass(e) {
  const isEventPath = checkEventPathForClass(e.path, 'booking-dropdown');
  if (!isEventPath) {
    $('#dropDownStart').classList.toggle('active');
  }
}


function checkEventPathForClass(path, selector) {
  for (item of path) {
    if (item.classList && item.classList.contains(selector)) {
      return true;
    }
  }
  return false;
}

$('body').addEventListener('click',(e) => {
  shouldToggleClass(e)
});

Upvotes: 0

Rasul SAFAROVITCH
Rasul SAFAROVITCH

Reputation: 58

You need to declare onclick function on entire document and than you can check if clicked Dom is datepicke or just remove active class from datepicker whenever click happens.

document.addEventListener("click", function(e){
    if( e.target.id == "dropDonStart" ){
        $('#dropDownStart').classList.toggle('active');
    }else{
        $('#dropDownStart').classList.remove('active');
    }
});

Not tested but should work.

Upvotes: 1

ComteZaroff
ComteZaroff

Reputation: 11

Isn't the good synthax :

`if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
    $('#dropDownStart').classList.add('active');
}`

?

Upvotes: 0

Related Questions