How to add HTML to a JavaScript alert box

Posted:

Okay, well, it's not really HTML,

Just add \n wherever you want a newline/line-break (<br>). So, put two (\n\n) for two newlines, like a paragraph. You can also use \t for a tab character. You could even just make an actual return or tab within the JavaScript string. View the source that creates the button below:

<input type="button" onclick="showalert()" value="Show alert box">

Check out this tutorial on escaping characters in a JavaScript alert.

To try an example:

  1. Go to w3schools' try-it=yourself=editor for the JavaScript alert() function.

  2. Then, copy and paste this code into the textarea:

    <html>
    <head>
    <script>
      function show_alert() {
        alert("Hello! I am an alert box!\n\nWith more than one paragraph. To make \
    this alert box, read the tutorial from whence it came. You can also \
    right-click to inspect elements on the page or to view the source of this \
    page and reverse engineer it. Or, get Firefox and Firebug. It's \
    sweet.\n\n\tHere's a tab-indented paragarph.\n\n    Here's a paragraph \
    indented with 4 spaces.");
    </script>
    </head>
    <body>
      <input type="button" onclick="show_alert()" value="Show alert box">
    </body>
    </html>
    
  3. Then, click the "Edit and Click Me >>" button at the top. After the page loads with the new html that you pasted, click the "Show alert box" button on the right.

Does it have newlines & tabs?


The better way to add HTML to your JavaScript alert box is... Well, I think you could just do it mainly with CSS.

Check out how Match.com does an alert box.

Right-clicking and selecting "Inspect Element" in Google Chrome (and using Firefox's plugin Firebug), I gathered some ideas in how to do this.