Skip to content

Instantly share code, notes, and snippets.

@Pacek
Created July 20, 2012 09:16
Show Gist options
  • Save Pacek/3149783 to your computer and use it in GitHub Desktop.
Save Pacek/3149783 to your computer and use it in GitHub Desktop.
Simple modal window jQuery plugin with XSS protection via Mustache.js
/*
* Simple modal window jQuery plugin with XSS protection via Mustache.js
*/
/*
Modal window templates
======================
Somewhere in the DOM
<div style="display: none;">
<div id="template">
<h1>{{ header }}</h1>
<p>{{ content }}</p>
</div>
<!-- other templates -->
</div>
Show modal window
=====================
var context = {
header : 'Some header',
content : 'Dangerous content <script>alert("xss")</script>'
}
$('#template').modal(context);
Result
======
Modal window with following content:
<div id="template">
<h1>Some header</h1>
<p>Dangerous content &lt;script&gt;alert(&quot;xss&quot;)&lt;&#x2F;script&gt;</p>
</div>
Close modal window
===================
$.fn.modal.hide();
CSS
===
#mask {
position: fixed;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
z-index: 5;
}
#modal {
position: fixed;
padding: 20px;
background: #fff;
z-index: 10;
box-shadow: 4px 4px 10px #333;
}
*/
(function($) {
/* public */
$.fn.modal = function(context) {
show(Mustache.render($(this[0]).html(), context));
return this;
};
$.fn.modal.hide = function() {
$('#modal, #mask').remove();
};
/* private */
function resize() {
var $modal = $('#modal');
$modal.css('margin-left', $(window).width()/2 - $modal.width()/2 -20)
.css('margin-top', $(window).height()/2 - $modal.height()/2 -20);
}
function bind() {
var self = this;
$('#modal a[rel="close"]').click(function(e) {
e.preventDefault();
$.fn.modal.hide();
});
$('#mask').click(function() {
$.fn.modal.hide();
});
$(document).keyup(function(e) {
if (e.keyCode == 27) {
$.fn.modal.hide();
}
});
$(window).resize(function() {
resize();
});
}
function show(content) {
$('<div id="modal">' + content + '</div><div id="mask"></div>')
.prependTo('body');
resize();
bind();
}
}) (jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment