Flash By Night Tutorials

Tutorial: Using simple lightboxes



What you will learn:

  • how to create a simple lightbox containing text, images and buttons
  • how to open and close a lightbox automatically

Prerequisites:

  • basic knowledge or experience with HTML or Javascript will be helpful

Required time:

1-2+ hours

Notes

They are useful for forms, quizzes, games or just to make a site more interactive. This will be a great project for anyone starting out in HTML5 and Javascript who wants a simple and fun project to build. Lightboxes focus a user's attention on specific content and prompt the user for input. You do not need any special software for this tutorial.

We will build a simple webpage with three variations:

1 Click a button to open a lightbox containing an image.
2 Click a button to open a lightbox containing an image. The user can then close the lightbox or navigate to another page.
3 A page with a lightbox that opens automatically after a few seconds and then closes automatically after a few seconds.

If you just want the source code without working through the tutorial, please go ahead. The source code for each variation is below:

SOURCE

SOURCE

SOURCE

 

HTML

Step 1 - Setting up the HTML document

Although you could use Dreamweaver or similar software, to create an HTML document, you don’t need any special software, you can simply use any text editor such as Textpad or Wordpad. Open your text editor and type:

<!DOCTYPE HTML>

This is the way that we begin all of our HTML5 documents. Now let’s fill out the document structure:

<!DOCTYPE HTML>
    <head>

		<link href="main.css"rel="stylesheet"type="text/css"/>
		<link href="featherlight.min.css"rel="stylesheet"type="text/css"/>
<script src="jquery.js"></script>
<script src="featherlight.min.js"></script>
<script src="controller.js"></script> </head>
<body> <div id="mybutton">See a cat</div>
<div id="dummy"></div> </body>
</html>

 

That's all the HTML we need and we're good to go.

In the HEAD of the document [2-11], we reference five external files that we are going to use. We will write two of these, and the other three are libraries that are freely available online

In the body of the document [12-17], we simply add a <div> that we will later style as a button containing the words See a cat and we add a empty <div> with the id DUMMY. We need this for technical reasons which will become clear later on.

Save the document as index.html. Test it out by opening it in a browser (right-click and choose Open With and choose a browser). There won't be anything to see yet, except the text 'See a cat'.



Project Management

Step 2

For this project, we are going to use the Featherlight framework, which allows us to create simple lightboxes quickly and easily.

Now we know that we will need the following files to build our project:

- index.html, which we have already done.
- main.css, which will hold the style information for our page
- featherlight.min.css - this is part of the Featherlight framework
- jquery.js, which is a popular library used with Javascript.
- featherlight.min.js - this is part of the Featherlight framework
- controller.js, which will contain the code that we will write

We will create main.css and controller.js ourselves and you can grab the other files from the source code link above. These files are also made available for free on the internet.

All of these files can be written or viewed in a text editor, just like index.html, so there’s no need for any special software. For this project, keep all the files in the same folder.

In addition, we will have the following graphical asset:

- cat.jpg - our image of a cat

You can use the cat image provided here (grab it from the source files above or save the image below) or you can use your own - it must be named cat.jpg and it should be 150 x 150 px in size.





CSS

Step 3 – Build a style sheet

We will use a CSS file to do the following:

1 Create a button
2 Create a container for content displayed in the lightbox
3 Hide our 'dummy' container, which the lightbox will be attached to.

Create a document entitled main.css and open it with any text editor and type the following:

#mybutton{
margin:auto;
margin-top:100px;
width:100px;
text-align:center;
background-color:#5C97BF;
height:24px;
padding:5px;
font-size:18px;
color:#fff;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
border-radius:5px;
}

#mybutton:hover{
opacity:.6;
}

#dummy{
display:none;
}
#lbinner{
width:150px;
height:170px;
}

Lines [1-14] contain style information for our customised button, including the width, height, font-size and background color. Line [3] adds a gap (a margin)of 100px at the top of the page. Line [12] ensure that the cursor becomes a pointer when you guide the mouse over the button, prompting the user to click.

Lines [16-18] create an effect when the user hovers the mouse over the button - the opacity changes to .6 (the maximum is 1). This helps to show the user that the button is active.

Lines [20-22] hide the content within our dummy divider. More on this later.

Then, lines [24-26] will be used to control the width and the height of the inner part of the lightbox. Because our photo is 150 x 150px, we need the size to match this (with a little extra height).

If you open index.html in a browser now, you will see the button, but if you click on it, nothing happens. We will fix that by writing a few lines of Javascript code.

 

Javascript


Step 6 – Creating the Javascript code

Our code will do the following three things:

1 Attach our lightbox to our hidden dummy 'div', where it will remain invisible until called.
2 Attach a 'listener' to our button, which will trigger a function when the button is clicked.
3 Display our lightbox when the button is clicked.

First, create a document called controller.js, save it and open it with a text editor or other program. Type the following:

$(document).ready(function () { 

});


This is how we begin and all of our code will fall between these two lines. It basically says that we will do the following as soon as the document is ‘ready’ in the browser.

Now for the rest of the code::

$(document).ready(function () {
$('#dummy').append('<div id="mylightbox"><div id="lbinner"><img src="cat.jpg"></div></div>');
$("#mybutton").on("click",showCat); function showCat(){
$.featherlight($('#mylightbox'), {});
}//showCat });

Line [3] attaches a div to our dummy (hidden) div, which contains an inner div with the id lbinner. You will remember that we have referenced this in the CSS. Inside this, we place our cat photo.

Line [4] says that on a "click" (or a tap on a mobile device) on the mybutton component, we will trigger the function showCat.

Lines [6-8] simply trigger the lightbox to appear. The cat photo has already been inserted and our featherlight library code will take care of the rest.

The only thing left to do now is to test it out. Open index.html in your favorite browser and you should see this:

When you press the button, you should see this:

To close the lightbox, simply press the X or click anywhere on the screen outside of the lightbox.


Variation 2

For our next trick, we will pop up the same lightbox, but this time we will add our own buttons and text to the lightbox. We will add a line that prompts the user: See more cats? followed by a YES and a NO button.

If the user presses YES, they will be taken to a Google Images search page and if they press NO, the lightbox will close.

To achieve this, we only need to amend two files: main.css to style our new buttons and lightbox size and controller.js to adjust our Javascript code. Let's look at the CSS code first:

CSS

Amend the original CSS code as follows:

.button{
margin:auto;
text-align:center;
background-color:#5C97BF;
padding:5px;
font-size:18px;
color:#fff;
font-family:Verdana, Geneva, sans-serif;
cursor:pointer;
border-radius:5px;
}
.button:hover{
opacity:.6;
}
#mybutton1{
margin-top:100px;
width:100px;
height:24px;
}


#mybutton2{
margin-top:5px;
width:60px;
float:left;
margin-right:10px;
height:35px;
}


#mybutton3{
margin-top:5px;
width:60px;
height:35px;
}


#dummy{
display:none;
}


#lbinner{
width:200px;
height:250px;
}

We use a slightly different technique here since we will have three buttons on the screen. The buttons will share some characteristics, such as color, but will have different widths and positioning.

First we create a button class which will apply style information to all buttons we use. When we define style information for a class, note that we precede the name with a dot (.) rather than a hash (#). Our button class is defined on lines [1-11] and [13-15].

Next we add our particular styling information for our SEE A CAT button on lines [17-21].

The first button in the pop-up box is #myButton2 and the style information is defined on lines [23-29]. Note that we tell the button to 'float' left, so that other objects (ie the other button) will be displayed to the right rather than on the following line. we also add a small right margin to add a space between it and the next button.

Lines [31-35] give style information for the last button.

Note that on lines [41-44], we make the lightbox a little bigger to accomodate the text and buttons.

 

Javascript


We will need some extra code in our controller.js file to add our extra functions:

$(document).ready(function () {
$("#mybutton").on("click",showCat); function showCat(){
$('#dummy').append('<div id="mylightbox"><div id="lbinner"></div></div>');
$('#lbinner').append('<img src="cat.jpg">');
$('#lbinner').append('<div>See more cats?</div>');
$('#lbinner').append('<div id="mybutton2" class="button">YES</div>');
$('#lbinner').append('<div id="mybutton3" class="button">NO</div>');

$.featherlight($('#mylightbox'), {
afterOpen: function(event){setClicks();}
});
}//showCat function setClicks(){
$(document).on('click', '#mybutton3', function(){
$("#lbinner").empty();
$.featherlight.current().close();
});

$(document).on('click', '#mybutton2', function(){
$("#lbinner").empty();
$.featherlight.current().close();
window.location.href = "http://www.google.com/search?tbm=isch&q=cats";
});
}//setclicks });

On line [3], we add a listener to our first button. If it is clicked (or tapped), we call the function showCat, detailed on lines [5-15].

Lines [6-10] use the append command to add the lightbox and then add our cat picture, our text prompt and our two buttons. We could do all this with a single line of code, but it is easier to read if we put it on separate lines.

On lines [10-12] we call the lightbox. In our statement, we include a function that will trigger after the lightbox opens (setClicks). This function is defined on lines [17-28] and attaches listener functions to the two buttons in the lightbox. We need to do this after the lightbox opens or the buttons will not exist yet.

Lines [18-21] add a listener function to #mybutton3 (our NO button). Upon clicking the NO button, the lightbox is emptied and closed. Line [20] closes the lightbox and is a useful piece of code to know.

Lines [23-27] add a listener function to #mybutton2 (our YES button). Remember, the question we posed to the user was "See more cats?", so on lines [24-25], we empty thlightbox and close it, as before, but on line [26], we call up a Google image search of... cats, of course.

Save the changes and open the index.html file in a browser. You should see the following:

 

Click on each button and observe what happens.

 

Variation 3

For our third and final variation, we will time the lightbox to open automatically after a set period of time and we will time it to close again after a set period of time. Practical uses of this would be to give feedback in a game, for example.

For this, we will amend the HTML, CSS and Javascript files.

 

HTML

Amend the original index.html file as follows:

<!DOCTYPE HTML>
    <head>

		<link href="main.css"rel="stylesheet"type="text/css"/>
		<link href="featherlight.min.css"rel="stylesheet"type="text/css"/>
<script src="jquery.js"></script>
<script src="featherlight.min.js"></script>
<script src="controller.js"></script> </head>
<body> <div id="mytext">You will see a cat</div>
<div id="dummy"></div> </body>
</html>

You will note that the only change from the original html file is line [14]. We have simply removed the button and added a line of text.

 

CSS

Amend the original main.css file as follows:

#mytext{
margin:auto;
margin-top:100px;
width:100px;
text-align:center;
}
#dummy{
display:none;
}
#lbinner{
width:150px;
height:170px;
}

You will notice that we have removed the styling for the button and added some simple styling information for our text [1-6], basically to center it on the screen. Lines [8-15] are unchanged from the original CSS.

Javascript


Open up the controller.js file and amend it as so:

$(document).ready(function () {
setTimeout(showCat,1500);
showCat(){
$('#dummy').append('<div id="mylightbox"><div id="lbinner"><img src="cat.jpg"></div></div>');
$.featherlight($('#mylightbox'), {});
setTimeout(function (){$.featherlight.current().close();},1500)
}//showCat });

You can see that we use the setTimout command to call our showCat function after an interval [3]. The number 1500 refers to milliseconds, ie 1.5 seconds. Adjust this number to adjust the time before the pop-up occurs.

Lines [7-8] should be familar by now and we add one more line, line[9], with another setTimeout command which will close the lightbox after a further 1.5 seconds.

And that's it! Test it out to check that it works.

 

More HTML5 tutorial resources:



I hope you enjoyed learning from this tutorial. There are plenty more tutorials at www.flashbynight.com/tutes.

These tutorials in particular are recommended:

Creating a multiple choice quiz.
Creating a picture quiz.
Creating a hangman game.

We also have some great games for you at www.flashbynight.com so stop by and check them out.

If you like this tutorial or anything else on Flash By Night, please show your appreciation by mentioning it on Facebook, Twitter, Pinterest, StumbleUpon or any other favorite social media. Follow Flash By Night at twitter.com/flashbynight.