DEV Community

artydev
artydev

Posted on

A tiny modal in Mithril

Here is a very simple modal implementation with Mithril.

You can test it here SimpleModal

<div id="modal"></div>
<button onclick="State.openDialog('nouveaute')">Info Home</button>
<button onclick="State.openDialog('legal')">News</button>
<button onclick="State.openDialog('apropos')"> About</button>

Enter fullscreen mode Exit fullscreen mode
.modal-shown {
  display: block;
}

.modal-hidden {
  display: none;
}

.modal {
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(222,0,0); /* Fallback color */
    background-color: rgba(220,0,0,0.5); /* Black w/ opacity */
}

  /* 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"] = m.trust(`
    <h2>Info Home</h2>
  `
);

Content["nouveaute"] = m.trust(`
    <h2>News</h2>
  `
);

Content["apropos"] = m.trust(`
    <h2>About</h2>
  `
);

window.State = {
  content: "",
  isOpen: false,
  openDialog: function(key){
    State.content = Content[key]
    State.isOpen = true;
    console.log(State.content)
    m.redraw()
  },
  closeDialog: function(){
    State.isOpen = false; 
  }
}

function setClassModal() {
  return  State.isOpen 
    ? "modal modal-shown" 
    : "modal modal-hidden"
}

export const  Modal = {
  oncreate : function(vnode){
    window.onclick = function(event) {
      if (event.target == vnode.dom) {
        State.closeDialog();
        m.redraw(); 
      }
    }
  },

  view: function() {
    return m("div", {class: setClassModal()}, 
      m("div.modal-content", [
        m("div", {
          onclick: State.closeDialog, 
          style:"text-align:right"}, 
        m("span", {class : "modal-close"}, "Close")),
        m("p", {}, State.content),       
      ])
    );
  }
}

m.mount(modal, Modal)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)