How to create your own jQuery Lightbox

Written by Tony Lea on Apr 26th, 2011 Views Report Post

Yeah, Yeah, I know there are so many jQuery lightbox plug-ins available today; however, if you want to create your own for any reason, I have created this video tutorial to show you the basic functionality of a jQuery lightbox. There are a lot more advanced features that may need to be added to this lightbox; although, for the sake of simplicity I wanted to keep this short and easy. If you are still a jQuery beginner, perhaps you may benefit from reading the article, jQuery 101 - The Basics.

Click here to check out the demo of this simple jQuery Lightbox or Click here to check out the video tutorial

You can find the code in this tutorial below:

index.html

<!DOCTYPE html>
<html>
<head>
	<title>Javascript Lightbox</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

	<h1>Hello Lightbox</h1>
	<button id="clickme">Open Lightbox</button>

	<div id="lightbox">
		<div id="lightbox_content">
			<div id="close">&times;</div>
			<h2>Javascript Lightbox</h2>
			<p>Hello from the lightbox :)</p>
		</div>
	</div>

	<script>
		document.getElementById('clickme').addEventListener('click', function(){
			document.getElementById('lightbox').className = 'open';
		});

		document.getElementById('close').addEventListener('click', function(){
			document.getElementById('lightbox').className = '';
		});

		document.getElementById('lightbox').addEventListener('click', function(e){
			if(e.target.id == 'lightbox'){
				document.getElementById('lightbox').className = '';
			}
		});
	</script>

</body>
</html>

style.css

#lightbox{
	position:fixed;
	width:100%;
	height:100%;
	top:0px;
	left:0px;
	background:rgba(0, 0, 0, 0.3);
	display:none;
}

#lightbox.open{
	display:block;
}

#lightbox_content{
	position:absolute;
	width:500px;
	height:400px;
	background:#ffffff;
	border-radius:3px;
	left:50%;
	top:50%;
	margin-left:-250px;
	margin-top:-200px;
	text-align:center;
}

#close{
	position:absolute;
	right:20px;
	top:20px;
	background:rgba(0, 0, 0, 0.2);
	height:20px;
	width:20px;
	border-radius:15px;
	text-align:center;
	color:#ffffff;
	cursor:pointer;
}

DEMO

Hope someone can find this tutorial useful ;)

Comments (0)