How to use HTML for jQuery dialog title

Latest version of jQuery UI doesn’t allow HTML as dialog title to avoid vulnerabilities. It only allows text. So if you want to show some icon or custom design for the title then you don’t have a way to do it from title property.

But we can do it by extending the dialog widget.

1st we will add an extra option to dialog property called titleIsHtml. We will set it as true if we want to use HTML for dialog title or false for text or even we can leave it so by default it will be text.

$(“#myDialog”).dialog({
        modal: true,
        title: “<div class=’widget-header widget-header-small’><h4 class=’smaller’><i class=’ic-file ‘></i> My Dialog</h4></div>”,
        titleIsHtml: true,
        autoOpen: false,
        width:800,
        height:’auto’
});

Now we are extending the dialog property like

$.widget(“ui.dialog”, $.extend({}, $.ui.dialog.prototype, {
        _title: function(title) {
            var $title = this.options.title || ‘&nbsp;’
            if( (“titleIsHtml” in this.options) && this.options.titleIsHtml == true )
                title.html($title);
            else title.text($title);
        }
}));

Here we are checking the titleIsHtml property of dialog, if it is set and true then we are setting dialog title using jQuery’s html() function which will allow to set HTML in dialog.

If titleIsHtml isn’t set or false then we are using jQuery’s text() function to set the title which will just put raw text as dialog title

Leave a comment