Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAshley Galante
4,668 PointsHow can I create a Lightbox in which one thumbnail opens up a scrolling gallery made of multiple images?
I want to create a gallery on my website but I have multiple images for each project. I'd like to organize them so that when someone clicks on the thumbnail of one project, it opens up all the related images in their own lightbox.
2 Answers
Erik McClintock
45,783 PointsAshley,
You could make a lightbox rather simply using some basic code from JavaScript (or jQuery, if you prefer), HTML, and CSS.
1) Build your image gallery as you normally would
1a) Apply a style of 'display: none' to the wrapper of your image gallery (lightbox)
2) If you're working in plain JavaScript, use .getElementById() to gain access to the appropriate thumbnail/button/element that you'll be using to trigger the lightbox
3) Again, if you're using plain JavaScript, use .addEventListener() to bind an event listener to the element that you just gained access to, and set it to watch the "click" event
3a) Have your event listener call a function that you'll write that, when called, will change the '.style.display' of your currently hidden lightbox from 'none' to 'block'
And voila! You've got yourself a lightbox.
Hope this helps!
Erik
Iain Simmons
Treehouse Moderator 32,305 PointsFurther to Erik's answer, you'd probably want to get, say, an array of the href
attributes of the image links (that presumably contain the full-size image URLs), and then use those as the src
attributes of the img
tags in the lightbox.
You would probably also want to add some buttons/links to go to the next/previous image from within the lightbox, and some method to close the lightbox.
Also, you'll need to style the lightbox appropriately, either by giving it a position: fixed
or similar. Make sure it is positioned 'above' the other elements on your page (either by placing just before the end of your body
tag, or using a CSS z-index
property).
There are obviously a number of things to consider to make an attractive, usable lightbox, which is why most people will opt to use a plugin, of which I'm sure there are thousands of options!
Here's a list of popular plugins on GitHub: https://github.com/search?o=desc&q=lightbox&s=stars&type=Repositories