Creating an Overlay Element with jQuery

I occasionally have the need to display an overlay element whenever I want to display some time of dialog in the context of my project.

Unfortunately, most plugins or third-party options are a little heavy for having to add a simple overlay. Here’s a function I’ve been using in the past couple of projects:

function create_overlay($) {

  var d = document.createElement('div');
  $(d).css({
	background: 'black',
	opacity: '0.5',
	width: '100%',
	height: '100%',
	position: 'absolute',
	top: 0,
	left: 0,
	display: 'none',
	zIndex: 100
  }).attr('id', 'overlay');
  $('body').append(d);

}

The function accepts the jQuery function as a parameter (in case noConflict() has been executed) and then appends the overlay to the DOM.

Usage would be as follows:

if($('#overlay').length === 0) {
  create_overlay($);
}
$('#overlay').fadeIn('fast');

2 Replies to “Creating an Overlay Element with jQuery”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.