Created
July 20, 2012 09:16
-
-
Save Pacek/3149783 to your computer and use it in GitHub Desktop.
Simple modal window jQuery plugin with XSS protection via Mustache.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 <script>alert("xss")</script></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