Combining two functions Pure JS

Viewed 52

How can I combine these two functions into one? Now I have two functions that do the same thing: close the search window on the site - by pressing escape and by pressing outside a certain .

    searchOverlay.addEventListener('keydown', function(event){
        if(event.key === "Escape"){
            body.classList.remove('search-opened');
            event.stopPropagation();
        }
    });

    searchOverlay.addEventListener('click', function (e) {
        if (e.target.closest('.search-inner') === null) {
            body.classList.remove('search-opened');
            e.stopPropagation();
        }
    });
}
2 Answers

You could even simply create an event listener that supports both cases

function removeSearchOpenedClass(event) {
  if (event.key === "Escape" || !event.target.closest(".search-inner")) {
    body.classList.remove('search-opened');
    event.stopPropagation(); 
  }
}
searchOverlay.addEventListener('keydown', removeSearchOpenedClass)
searchOverlay.addEventListener('click', removeSearchOpenedClass)

You can declare a function and call it in both callbacks.

function doStuff(e){
    body.classList.remove('search-opened');
    e.stopPropagation();
}

searchOverlay.addEventListener('keydown', function(event){
    if(event.key === "Escape"){
        doStuff(event)
    }
});

searchOverlay.addEventListener('click', function (e) {
    if (e.target.closest('.search-inner') === null) {
        doStuff(e)
    }
});
Related