DEV Community

artydev
artydev

Posted on

Simple Modal in pure Javascript

When you can't use the library you want, you have to deal with what you have...and in fact it's sometimes challenging :-)

Here is then the vanilla version of my previous Mithril version.

You can test it here : VanillaModal

<div id="modal"></div>

<div>
  <h1>Modal in pure JS</h1>

  <div id="triggerModal">
    <button modal="legal" >  
      Legal
    </button>
    <button modal="nouveaute" >  
      News
    </button>
    <button  modal="apropos" >
      About
    </button>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode
.modal-shown {
  display: block;
}

.modal-hidden {
  display: none;
}

.modal {
    position: fixed; 
    z-index: 1; 
    padding-top: 100px;
    left: 0;
    top: 0;
    width: 100%; 
    height: 100%; 
    overflow: auto; 
    background-color: rgb(222,0,0);
    background-color: rgba(220,0,0,0.5); 
}

  /* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    max-width: 960px;
}

.modal-close {

  cursor: pointer;
  right:0;
}

.modal-close:hover {
  box-shadow: 0 0 5px rgba(0,0,0,0.4);
}
Enter fullscreen mode Exit fullscreen mode
const Content = {};

Content["legal"] = `
    <h2>Info Home</h2>
`

Content["nouveaute"] = `
    <h2>News</h2>
`

Content["apropos"] = `
    <h2>About</h2>
`

window.State = {
  content: null,
  isOpen: false,
  openDialog: function(key){
    State.content = Content[key]
    State.isOpen = true;
    view()
  },
  closeDialog: function(){
    State.isOpen = false;
    view()
  }
}

function view () {
  var modalCls =  State.isOpen 
    ? "modal modal-shown"  
    : "modal modal-hidden"
  modal.innerHTML =  `
    <div class="${modalCls}">
      <div class="modal-content">
        <div style="text-align:right" onclick="State.closeDialog()">
          <span class="modal-close">Close</span>
        </div>
        <p>${State.content}</p>
      </div>
    </div>
  `
}

triggerModal.addEventListener("click", function (e) {
  var modal  = e.target.getAttribute("modal")
  modal && State.openDialog(modal)
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)