[javascript] How to change the style of alert box?

I need to change the style of the "OK" Button in an alert box.

_x000D_
_x000D_
<head>_x000D_
    <script type="text/javascript">_x000D_
        function show_alert() {_x000D_
            alert("Hello! I am an alert box!");_x000D_
        }_x000D_
    </script>_x000D_
</head>_x000D_
<body>_x000D_
    <input type="button" onclick="show_alert()" value="Show alert box" />_x000D_
</body>
_x000D_
_x000D_
_x000D_

This question is related to javascript css

The answer is


Not possible. If you want to customize the dialog's visual appearance, you need to use a JS-based solution like jQuery.UI dialog.


I don't think you could change the style of browsers' default alert boxes.

You need to create your own or use a simple and customizable library like xdialog. Following is a example to customize the alert box. More demos can be found here.

_x000D_
_x000D_
function show_alert() {_x000D_
    xdialog.alert("Hello! I am an alert box!");_x000D_
}
_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.css"/>_x000D_
    <script src="https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.js"></script>_x000D_
    _x000D_
    <style>_x000D_
        .xd-content .xd-body .xd-body-inner {_x000D_
            max-height: unset;_x000D_
        }_x000D_
        .xd-content .xd-body p {_x000D_
            color: #f0f;_x000D_
            text-shadow: 0 0 5px rgba(0, 0, 0, 0.75);_x000D_
        }_x000D_
        .xd-content .xd-button.xd-ok {_x000D_
            background: #734caf;_x000D_
        }_x000D_
    </style>_x000D_
</head>_x000D_
<body>_x000D_
    <input type="button" onclick="show_alert()" value="Show alert box" />_x000D_
</body>
_x000D_
_x000D_
_x000D_


You need to create your own alert box like this:

_x000D_
_x000D_
function jAlert(text, customokay){_x000D_
 document.getElementById('jAlert_content').innerHTML = text;_x000D_
    document.getElementById('jAlert_ok').innerHTML = customokay;_x000D_
    document.body.style.backgroundColor = "gray";_x000D_
    document.body.style.cursor="wait";_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
jAlert("Stop! Stop!", "<b>Okay!</b>");
_x000D_
#jAlert_table, #jAlert_th, #jAlert_td{_x000D_
    border: 2px solid blue;_x000D_
    background-color:lightblue;_x000D_
    border-collapse: collapse;_x000D_
    width=100px;_x000D_
}_x000D_
_x000D_
#jAlert_th, #jAlert_td{_x000D_
    padding:5px;_x000D_
    padding-right:10px;_x000D_
    padding-left:10px;_x000D_
}_x000D_
_x000D_
#jAlert{_x000D_
    /* Position fixed */_x000D_
    position:fixed;_x000D_
    /* Center it! */_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    margin-top: -50px;_x000D_
    margin-left: -100px;_x000D_
}
_x000D_
<p>TEXT</p>_x000D_
<div id="jAlRem">_x000D_
    <div id="jAlert">_x000D_
        <table id="jAlert_table">_x000D_
            <tr id="jAlert_tr">_x000D_
                <td id="jAlert_td">  <p id="jAlert_content"></p>  </td>_x000D_
                <td id="jAlert_td">  <button id='jAlert_ok'  onclick="jAlertagree()"></button>  </td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
<p>TEXT</p>_x000D_
_x000D_
_x000D_
<script>_x000D_
function jAlertagree(){_x000D_
    var parent = document.getElementById('jAlRem');_x000D_
    var child = document.getElementById('jAlert');_x000D_
    parent.removeChild(child);_x000D_
    document.body.style.backgroundColor="white";_x000D_
    document.body.style.cursor="default";_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

The js portion gets the element in the HTML to create the alert box, then deletes it after the user clicks ok.

You can call the alert using jAlert("Custom Text", "Ok!");


I tried to use script for alert() boxes styles using java-script.Here i used those JS and CSS.

Refer this coding JS functionality.

var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";

if(document.getElementById) {
    window.alert = function(txt) {
        createCustomAlert(txt);
    }
}

function createCustomAlert(txt) {
    d = document;

    if(d.getElementById("modalContainer")) return;

    mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
    mObj.id = "modalContainer";
    mObj.style.height = d.documentElement.scrollHeight + "px";

    alertObj = mObj.appendChild(d.createElement("div"));
    alertObj.id = "alertBox";
    if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
    alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
    alertObj.style.visiblity="visible";

    h1 = alertObj.appendChild(d.createElement("h1"));
    h1.appendChild(d.createTextNode(ALERT_TITLE));

    msg = alertObj.appendChild(d.createElement("p"));
    //msg.appendChild(d.createTextNode(txt));
    msg.innerHTML = txt;

    btn = alertObj.appendChild(d.createElement("a"));
    btn.id = "closeBtn";
    btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
    btn.href = "#";
    btn.focus();
    btn.onclick = function() { removeCustomAlert();return false; }

    alertObj.style.display = "block";

}

function removeCustomAlert() {
    document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}

And CSS for alert() Box

#modalContainer {
    background-color:rgba(0, 0, 0, 0.3);
    position:absolute;
    width:100%;
    height:100%;
    top:0px;
    left:0px;
    z-index:10000;
    background-image:url(tp.png); /* required by MSIE to prevent actions on lower z-index elements */
}

#alertBox {
    position:relative;
    width:300px;
    min-height:100px;
    margin-top:50px;
    border:1px solid #666;
    background-color:#fff;
    background-repeat:no-repeat;
    background-position:20px 30px;
}

#modalContainer > #alertBox {
    position:fixed;
}

#alertBox h1 {
    margin:0;
    font:bold 0.9em verdana,arial;
    background-color:#3073BB;
    color:#FFF;
    border-bottom:1px solid #000;
    padding:2px 0 2px 5px;
}

#alertBox p {
    font:0.7em verdana,arial;
    height:50px;
    padding-left:5px;
    margin-left:55px;
}

#alertBox #closeBtn {
    display:block;
    position:relative;
    margin:5px auto;
    padding:7px;
    border:0 none;
    width:70px;
    font:0.7em verdana,arial;
    text-transform:uppercase;
    text-align:center;
    color:#FFF;
    background-color:#357EBD;
    border-radius: 3px;
    text-decoration:none;
}

/* unrelated styles */

#mContainer {
    position:relative;
    width:600px;
    margin:auto;
    padding:5px;
    border-top:2px solid #000;
    border-bottom:2px solid #000;
    font:0.7em verdana,arial;
}

h1,h2 {
    margin:0;
    padding:4px;
    font:bold 1.5em verdana;
    border-bottom:1px solid #000;
}

code {
    font-size:1.2em;
    color:#069;
}

#credits {
    position:relative;
    margin:25px auto 0px auto;
    width:350px; 
    font:0.7em verdana;
    border-top:1px solid #000;
    border-bottom:1px solid #000;
    height:90px;
    padding-top:4px;
}

#credits img {
    float:left;
    margin:5px 10px 5px 0px;
    border:1px solid #000000;
    width:80px;
    height:79px;
}

.important {
    background-color:#F5FCC8;
    padding:2px;
}

code span {
    color:green;
}

And HTML file:

<input type="button" value = "Test the alert" onclick="alert('Alert this pages');" />

And also View this DEMO: JSFIDDLE and DEMO RESULT IMAGE

enter image description here


I use sweetalert2 library. It's really simple, a lot of customization, modern, animated windows, eye-catching, and also nice design.

Swal.fire({
  icon: 'error',
  title: 'Oops...',
  text: 'Something went wrong!',
  footer: '<a href>Why do I have this issue?</a>'
})

Check this link


Styling alert()-boxes ist not possible. You could use a javascript modal overlay instead.


Option1. you can use AlertifyJS , this is good for alert

enter image description here

enter image description here

Option2. you start up or just join a project based on webapplications, the design of interface is maybe good. Otherwise this should be changed. In order to Web 2.0 applications you will work with dynamic contents, many effects and other stuff. All these things are fine, but no one thought about to style up the JavaScript alert and confirm boxes. Here is the they way

create simple js file name jsConfirmStyle.js. Here is simple js code

ie5=(document.getElementById&&document.all&&document.styleSheets)?1:0;
nn6=(document.getElementById&&!document.all)?1:0;

xConfirmStart=800;
yConfirmStart=100;

if(ie5||nn6) {
if(ie5) cs=2,th=30;
else cs=0,th=20;
document.write(
    "<div id='jsconfirm'>"+
        "<table>"+
            "<tr><td id='jsconfirmtitle'></td></tr>"+
            "<tr><td id='jsconfirmcontent'></td></tr>"+
            "<tr><td id='jsconfirmbuttons'>"+
                "<input id='jsconfirmleft' type='button' value='' onclick='leftJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
                "&nbsp;&nbsp;"+
                "<input id='jsconfirmright' type='button' value='' onclick='rightJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
            "</td></tr>"+
        "</table>"+
    "</div>"
);
 }

           document.write("<div id='jsconfirmfade'></div>");


function leftJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=leftJsConfirmUri;
}
function rightJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=rightJsConfirmUri;
}
function confirmAlternative() {
if(confirm("Scipt requieres a better browser!"))       document.location.href="http://www.mozilla.org";
 }

leftJsConfirmUri = '';
rightJsConfirmUri = '';

/**
 * Show the message/confirm box
*/
function showConfirm(confirmtitle,confirmcontent,confirmlefttext,confirmlefturi,confirmrighttext,confirmrighturi)  {
document.getElementById("jsconfirmtitle").innerHTML=confirmtitle;
document.getElementById("jsconfirmcontent").innerHTML=confirmcontent;
document.getElementById("jsconfirmleft").value=confirmlefttext;
document.getElementById("jsconfirmright").value=confirmrighttext;
leftJsConfirmUri=confirmlefturi;
rightJsConfirmUri=confirmrighturi;
xConfirm=xConfirmStart, yConfirm=yConfirmStart;
if(ie5) {
    document.getElementById("jsconfirm").style.left='25%';
    document.getElementById("jsconfirm").style.top='35%';
}
else if(nn6) {
    document.getElementById("jsconfirm").style.top='25%';
    document.getElementById("jsconfirm").style.left='35%';
}
else confirmAlternative();
}

Create simple html file

<html>
<head>
<title>jsConfirmSyle</title>
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<script type="text/javascript" src="jsConfirmStyle.js"></script>
<script type="text/javascript">

 function confirmation() {
 var answer = confirm("Wanna visit google?")
 if (answer){
    window.location = "http://www.google.com/";
}
}
  </script>
   <style type="text/css">
    body {
  background-color: white;
   font-family: sans-serif;
  }
#jsconfirm {
border-color: #c0c0c0;
border-width: 2px 4px 4px 2px;
left: 0;
margin: 0;
padding: 0;
position: absolute;
top: -1000px;
z-index: 100;
}

#jsconfirm table {
background-color: #fff;
border: 2px groove #c0c0c0;
height: 150px;
width: 300px;
}

#jsconfirmtitle {
background-color: #B0B0B0;
font-weight: bold;
height: 20px;
text-align: center;
}

#jsconfirmbuttons {
height: 50px;
text-align: center;
}

#jsconfirmbuttons input {
background-color: #E9E9CF;
color: #000000;
font-weight: bold;
width: 125px;
height: 33px;
padding-left: 20px;
}

#jsconfirmleft{
background-image: url(left.png);
}

#jsconfirmright{
background-image: url(right.png);
}
</style>

 <p>
<a href="#"  onclick="javascript:showConfirm('Please confirm','Are you really sure to visit google?','Yes','http://www.google.com','No','#')">JsConfirmStyled</a> </p>
<p><a href="#" onclick="confirmation()">standard</a></p>


</body>
 </html>

I know this is an older post but I was looking for something similar this morning. I feel that my solution was much simpler after looking over some of the other solutions. One thing is that I use font awesome in the anchor tag.

I wanted to display an event on my calendar when the user clicked the event. So I coded a separate <div> tag like so:

<div id="eventContent" class="eventContent" style="display: none; border: 1px solid #005eb8; position: absolute; background: #fcf8e3; width: 30%; opacity: 1.0; padding: 4px; color: #005eb8; z-index: 2000; line-height: 1.1em;">
        <a style="float: right;"><i class="fa fa-times closeEvent" aria-hidden="true"></i></a><br />
        Event: <span id="eventTitle" class="eventTitle"></span><br />
        Start: <span id="startTime" class="startTime"></span><br />
        End: <span id="endTime" class="endTime"></span><br /><br />
</div>

I find it easier to use class names in my jquery since I am using asp.net.

Below is the jquery for my fullcalendar app.

<script>
    $(document).ready(function() {
        $('#calendar').fullCalendar({
            googleCalendarApiKey: 'APIkey',
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            events: {
                googleCalendarId: '@group.calendar.google.com'
            },
            eventClick: function (calEvent, jsEvent, view) {
                var stime = calEvent.start.format('MM/DD/YYYY, h:mm a');
                var etime = calEvent.end.format('MM/DD/YYYY, h:mm a');
                var eTitle = calEvent.title;
                var xpos = jsEvent.pageX;
                var ypos = jsEvent.pageY;
                $(".eventTitle").html(eTitle);
                $(".startTime").html(stime);
                $(".endTime").html(etime);
                $(".eventContent").css('display', 'block');
                $(".eventContent").css('left', '25%');
                $(".eventContent").css('top', '30%');
                return false;
            }
        });
        $(".eventContent").click(function() {
            $(".eventContent").css('display', 'none');
        });
    });
</script>

You must have your own google calendar id and api keys.

I hope this helps when you need a simple popup display.


I use SweetAlert, It's Awesome, You will get lots of customization option as well as all callbacks

Screenshot

swal("Here's a message!", "It's pretty, isn't it?");

enter image description here


One option is to use altertify, this gives a nice looking alert box.

Simply include the required libraries from here, and use the following piece of code to display the alert box.

alertify.confirm("This is a confirm dialog.",
  function(){
    alertify.success('Ok');
  },
  function(){
    alertify.error('Cancel');
  });

The output will look like this. To see it in action here is the demo

enter image description here


I use AlertifyJS to style my dialogues.

_x000D_
_x000D_
alertify.alert('Ready!');_x000D_
alertify.YoutubeDialog || alertify.dialog('YoutubeDialog',function(){_x000D_
    var iframe;_x000D_
    return {_x000D_
        // dialog constructor function, this will be called when the user calls alertify.YoutubeDialog(videoId)_x000D_
        main:function(videoId){_x000D_
            //set the videoId setting and return current instance for chaining._x000D_
            return this.set({ _x000D_
                'videoId': videoId_x000D_
            });_x000D_
        },_x000D_
        // we only want to override two options (padding and overflow)._x000D_
        setup:function(){_x000D_
            return {_x000D_
                options:{_x000D_
                    //disable both padding and overflow control._x000D_
                    padding : !1,_x000D_
                    overflow: !1,_x000D_
                }_x000D_
            };_x000D_
        },_x000D_
        // This will be called once the DOM is ready and will never be invoked again._x000D_
        // Here we create the iframe to embed the video._x000D_
        build:function(){           _x000D_
            // create the iframe element_x000D_
            iframe = document.createElement('iframe');_x000D_
            iframe.frameBorder = "no";_x000D_
            iframe.width = "100%";_x000D_
            iframe.height = "100%";_x000D_
            // add it to the dialog_x000D_
            this.elements.content.appendChild(iframe);_x000D_
_x000D_
            //give the dialog initial height (half the screen height)._x000D_
            this.elements.body.style.minHeight = screen.height * .5 + 'px';_x000D_
        },_x000D_
        // dialog custom settings_x000D_
        settings:{_x000D_
            videoId:undefined_x000D_
        },_x000D_
        // listen and respond to changes in dialog settings._x000D_
        settingUpdated:function(key, oldValue, newValue){_x000D_
            switch(key){_x000D_
               case 'videoId':_x000D_
                    iframe.src = "https://www.youtube.com/embed/" + newValue + "?enablejsapi=1";_x000D_
                break;   _x000D_
            }_x000D_
        },_x000D_
        // listen to internal dialog events._x000D_
        hooks:{_x000D_
            // triggered when the dialog is closed, this is seperate from user defined onclose_x000D_
            onclose: function(){_x000D_
                iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}','*');_x000D_
            },_x000D_
            // triggered when a dialog option gets update._x000D_
            // warning! this will not be triggered for settings updates._x000D_
            onupdate: function(option,oldValue, newValue){_x000D_
                switch(option){_x000D_
                    case 'resizable':_x000D_
                        if(newValue){_x000D_
                            this.elements.content.removeAttribute('style');_x000D_
                            iframe && iframe.removeAttribute('style');_x000D_
                        }else{_x000D_
                            this.elements.content.style.minHeight = 'inherit';_x000D_
                            iframe && (iframe.style.minHeight = 'inherit');_x000D_
                        }_x000D_
                    break;    _x000D_
                }    _x000D_
            }_x000D_
        }_x000D_
    };_x000D_
});_x000D_
//show the dialog_x000D_
alertify.YoutubeDialog('GODhPuM5cEE').set({frameless:true});
_x000D_
<!-- JavaScript -->_x000D_
<script src="//cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>_x000D_
<!-- CSS -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css"/>_x000D_
<!-- Default theme -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.min.css"/>_x000D_
<!-- Default theme -->_x000D_
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.rtl.min.css"/>
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
<head>_x000D_
  _x000D_
_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
  _x000D_
    <script type="text/javascript">_x000D_
  _x000D_
_x000D_
$(function() {_x000D_
    $( "#dialog" ).dialog({_x000D_
      autoOpen: false,_x000D_
      show: {_x000D_
        effect: "blind",_x000D_
        duration: 1000_x000D_
      },_x000D_
      hide: {_x000D_
        effect: "explode",_x000D_
        duration: 1000_x000D_
      }_x000D_
    });_x000D_
 _x000D_
    $( "#opener" ).click(function() {_x000D_
      $( "#dialog" ).dialog( "open" );_x000D_
    });_x000D_
  });_x000D_
    </script>_x000D_
</head>_x000D_
<body>_x000D_
   <div id="dialog" title="Basic dialog">_x000D_
   <p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
  </div>_x000D_
 _x000D_
  <button id="opener">Open Dialog</button>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_