This is my first attempt at a jQuery plugin, which is a simple modal window. I'm keen for feedback of whether I've got the principle correct, the usability of the plugin and any improvements that could be made.
Here is a working JSBin.
The plugin instructions:
Add one or more elements that will launch a modal when clicked. Give these a class of modal-open.
Add elements to display in the modal window. These should go in a
</div>withclass="overlay-message hide". and thedivneeds anid.Add a data-target attribute to the modal-open element(s) made in 1. The value of this should be the same as the id of the overlay-message element made in 2.
Add links to jQuery, overlay.js and overlay.css
Call
$('.modal-open').modalise()
The JS code:
(function ( $ ) {
$.fn.modalise = function( options ) {
// Add and initialise the overlay background
$('body').append('<div class="overlay modal-close hide"></div>');
$('.modal-close').on('click',function(){
$('.overlay').toggleClass("hide");
$('.overlay-message').addClass("hide");
console.log('clicked');
});
// Options for the plugin
var settings = $.extend({
// Default options
width: "700px",
closeButton: true
}, options );
return this.each(function(index){
// Dom elements
var openButton = $(this),
targetSelector = '#' + $(this).attr('data-target');
// Add and initiate close button
if(settings.closeButton){
$(targetSelector).prepend('<a href="#" class="modal-close btn">X</a>').find('.modal-close').on('click',function(){
$('.overlay').addClass("hide");
$('.overlay-message').addClass("hide");
});
}
// Show the relevant modal window on clicking the open button
openButton.on('click',function(){
var targetSelector = '#' + $(this).attr('data-target');
$(targetSelector + ', .overlay').toggleClass("hide");
});
});
};
}( jQuery ));
The CSS code:
.overlay{
width: 100%;
height: 100%;
background: #000000;
filter: alpha(opacity=80);
background: rgba(0,0,0,0.8);
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1000;
}
.overlay-message{
padding: 20px;
background: white;
position: absolute;
width: 660px;
left: 50%;
margin-left: -350px;
top: 10%;
z-index: 10000;
}
.hide{
display: none;
}
.modal-close.btn{
position: absolute;
right: 8px;
top: 5px;
color: black;
background: none;
text-decoration: none;
}
.modal-open{
cursor: pointer;
}
@media only screen and (max-width: 767px){
.overlay-message{
width: auto;
left: 5%;
right: 5%;
margin-left: 0;
}
}