Modals in Pure ES6 JavaScript

A lot of web developers rely on huge libraries to do anything more complex than displaying text and basic formatting. While it is great to not have to reinvent the wheel whenever you start a new project, this approach is not without it's drawbacks. I've seen developers struggle to understand code when they get outside of their curated garden of libraries.

There's something to be said about using only the standard interfaces, even for a language like JavaScript. You don't ever run into the "asking for a banana and getting Harambe (the whole gorilla)" situation. And with ES6 doing a lot to improve JavaScript's standard offerings, there's never been a better time to go this route than now.

Take for modals for an example. They're pretty much on every webpage designed after 1999 and they're in every major UI library (bootstrap, foundation, you name it). Adding one of these libraries adds thousands of lines of code and a whole new interface for the programmer to understand. In reality, you can add modals in under 20 lines of JS.

 class Modal {
  constructor(overlay) {
    this.overlay = overlay;
    const closeButton = overlay.querySelector('.button-close')
    closeButton.addEventListener('click', this.close.bind(this));
    overlay.addEventListener('click', e => {
      if (e.srcElement.id === this.overlay.id) {
        this.close();
      }
    });
  }
  open() {
    this.overlay.classList.remove('is-hidden');
  }

  close() {
    this.overlay.classList.add('is-hidden');
  }
}