MDN self-hosted library · e01.org

Build your own function

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
alert("This is a message");
html
   <!doctype html>
   <html lang="en-US">
     <head>
       <meta charset="utf-8" />
       <meta name="viewport" content="width=device-width" />
       <title>Function start</title>
       <style>
         .msgBox {
           position: absolute;
           top: 50%;
           left: 50%;
           transform: translate(-50%, -50%);
           width: 200px;
           border-radius: 10px;
           background-color: #eeeeee;
           background-image: linear-gradient(
             to bottom,
             rgb(0 0 0 / 0),
             rgb(0 0 0 / 0.1)
           );
         }

         .msgBox p {
           line-height: 1.5;
           padding: 10px 20px;
           color: #333333;
         }

         .msgBox button {
           background: none;
           border: none;
           position: absolute;
           top: 0;
           right: 0;
           font-size: 1.1rem;
           color: #aaaaaa;
         }
       </style>
     </head>
     <body>
       <button>Display message box</button>

       <script></script>
     </body>
   </html>
js
   function displayMessage() {
     // …
   }
js
   const body = document.body;

   const panel = document.createElement("div");
   panel.setAttribute("class", "msgBox");
   body.appendChild(panel);

   const msg = document.createElement("p");
   msg.textContent = "This is a message box";
   panel.appendChild(msg);

   const closeBtn = document.createElement("button");
   closeBtn.textContent = "x";
   panel.appendChild(closeBtn);

   closeBtn.addEventListener("click", () => body.removeChild(panel));
js
const body = document.body;
js
const panel = document.createElement("div");
panel.setAttribute("class", "msgBox");
body.appendChild(panel);
js
const msg = document.createElement("p");
msg.textContent = "This is a message box";
panel.appendChild(msg);

const closeBtn = document.createElement("button");
closeBtn.textContent = "x";
panel.appendChild(closeBtn);
js
closeBtn.addEventListener("click", () => body.removeChild(panel));
html
<div class="msgBox">
  <p>This is a message box</p>
  <button>x</button>
</div>
js
   displayMessage();
js
   const btn = document.querySelector("button");
js
   btn.addEventListener("click", displayMessage);