JQuery: Pop Up Modal That Includes its Own HTML

JQuery: Pop Up Modal That Includes its Own HTML

On my day job, there were several times that I needed to use JQuery's Pop modal that include its own HTML instead of having to code it on the main page and include that part in the modal itself. I find this approach to be much cleaner since I get to separate the modal and main page part. At this moment, right now is that time.

Since I don't use the modal this way often enough, I don't remember on top of my head how to use it and therefore I'd spent sometime googling. And this usually take me sometime to get to the part that fits my need. Digging through my applications to look at what I did take some time too. So since I've done it this way way too many times, I thought I'd just blog it here just in case it could be useful for anybody reading this post and also for me to reference in the future.

Once you've included the jquery.js in your page, to add the modal you can use this:

$("[Your HTML code]").dialog({[Dialog options]});

That's about it. On my case, as example that I've used it to display modal image, it's as follow:

$("<div><img src=\"[Your image location]\" /></div>").dialog({position:"center", top:'0', width:"auto"});

Another time, when I needed to have a "Yes" and "No" dialog, I used it as follow:

var message = "Are you sure ....?";
$("<div></div>").dialog({
    buttons: {
        "Yes": function() {
           //Other code you'd like to run before closing.
            $(this).dialog("close");            
        },
        "No": function() {
            //Other code you'd like to run before closing.
            $(this).dialog("close");
        }
    },
    close: function(event, ui) { $(this).remove(); },
    open: function(event, ui) { $(this).parent().css({[/*Your css styling goes here, as an example,*/ 'top': 5 ]}); },
    resizeable: false, //or true, depending on your need
    title: "Your own title for the modal",
    modal: true
}).text(message); //From the earlier var message

I think that's it if you'd like to use it generically and does not want to use javascript's alert and confirm. I hope this can be useful for you as it will be for me.

As a reminder, don't forget to add:

<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript" src="/jquery/jquery-ui.js"></script>

on your page.

Also, unlike alert/confirm of plain vanilla javascript, the modal appears on the main html itself and not a window of its own on top of the browser. Just in case you'd like to have a popup, stand alone window notification, you won't be able to use this.