jQuery for Complete Beginners: Part 4

Welcome back to jQuery for Beginners. Just a quick recap first – in the first two weeks we covered the very basics of jQuery and interacting with elements. Last time round we made an accordion – something which taught us a few of the jQuery special animation functions that are built in to jQuery. Today we will be using those functions and a bit more as we look at creating a nice looking Gallery page, built with HTML and CSS, and then adding some nice interactive effects with jQuery.

 

Be sure to check the previous parts:

You can see the live demo here. You can also download the source code here.

Firstly, open up a new HTML page, add the basic HTML code and then include jQuery like so:

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">

	</script>

I’ve also added another script tag that is blank. This is where our code will go. Notice that when I included jQuery from the Google CDN (we covered this back in the first post) I’ve used “jquery/1/jquery.min.js”. Using just “1” means we will automatically be given the most recent version of jQuery, until we get to jQuery 2, which is a fair way off for now. You could be much more specific, of course, if you wished, but for me it makes logical sense to keep up to date with the most recent versions.

Now we’ve got that sorted, I’ve got a basic HTML structure for our gallery, ready made with five images. If you go to the bottom of this post, you can download them, along with the completed code.

div id="gallery">
		<div class="galleryitem"><img src="image1.jpg" alt="A beautiful Sunset over a field" /><p>A beautiful Sunset over a field</p></div>
		<div class="galleryitem"><img src="image2.jpg" alt="Some penguins on the beach" /><p>Some penguins on the beach</p></div>
		<div class="galleryitem"><img src="image3.jpg" alt="The sun trying to break through the clouds" /><p>The sun trying to break through the clouds</p></div>
		<div class="galleryitem"><img src="image4.jpg" alt="Palm tress on a sunny day" /><p>Palm tress on a sunny day</p></div>
		<div class="galleryitem"><img src="image5.jpg" alt="The sun bursting through the tall grass" /><p>The sun bursting through the tall grass</p></div>
	</div>

Next up we will apply some CSS styling to make it look nicer. Seeing as this is a jQuery tutorial, I’m not going to explain much of this. Essentially I’m just adding a border, styling the font and floating the images so they display next to each other.

	#gallery {width: 960px; margin: 0 auto;}
		.galleryitem {width: 300px; height: 300px;float: left; font-family: Lucida Sans Unicode, Arial; font-style: italic; font-size: 13px; border: 5px solid black; margin: 3px;}
		.galleryitem img {width: 300px;}
		.galleryitem p {text-indent: 15px;}

And your page should look something like this:

Looks pretty good!

Our next step is going to be some jQuery. At last! We are going to remove the paragraphs and make them appear on hover, with some nice CSS styling to make them look really nice. What I’ve done is create a CSS id which we will apply to a paragraph when the corresponding image is hovered over:

	#galleryhoverp { margin-top: -55px; background-color: black; opacity: 0.5;
		-moz-opacity: 0.5;
		filter:alpha(opacity=50); height: 40px; color: white; padding-top: 10px;}

So our first step is to hide all the paragraphs and then resize our gallery items so just the image is displayed. We’ll also save all our gallery items to a variable for later usage.

	$('p').hide();
	var galleryItems = $('.galleryitem');
		galleryItems.css('height', '200px');

And now lets add an effect for when the gallery item is hovered over. Firstly lets find all the images and save them.

var images = $('.galleryitem').find('img');

The hover function is slightly unusual in that it takes two functions. The first is what should happen when the image is hovered over, the second when the mouse stops hovering over that image.

	galleryItems.hover(
			function() {
				//when hovered over
			},
			function() {
				//when hovered ends
			}
		)

The code is very simple. We just select the next paragraph using the next() function, show it and then give it that id we created a while back. On the hover-out function, we just do the exact opposite:

galleryItems.hover(
			function() {
				$(this).children("id").next('p').show().attr('id', 'galleryhoverp');
			},
			function() {
				$(this).children("id").next('p').hide().attr('id', '');
			}
		)

And there you go! If you try it out now you should see the paragraphs show when you hover over, and then leave when you change to a different image.

There is one more effect we will add. When you click on an image, it should enlarge, fill the centre of the screen and all the other images disappear. Again, I’m creating some CSS which we will add to the image we want to display:

#singleimagedisplay {width: 800px;}
#singleimagedisplay img {width: 800px;}
#singleimagedisplay a {float: right; color: white;}

We’ll add this code to the image’s parent – the div with a class of ‘galleryitem’. The code for the entire click event is below:

	images.click(function() {
			$(this).parent().attr('id', 'singleimagedisplay').css('height', $(this).height()).siblings().hide();
			$(this).next('p').show().html($(this).next('p').html() + '<a href="jquery1.html">Back</a>');

		})

So, when each image is clicked, these are the steps we take:
1. Give the id of ‘singleimagedisplay’ to the image’s parent.
2. Set the height of the image parent to the height of the image. This uses jQuery’s height() function, which finds the height of the specified item.
3. Select all the other gallery item divs using siblings() and hide them.
4. Edit the paragraph that comes with the image to have a link on the end, which links back to the home page. jQuery’s HTML function allows us to edit the HTML code with in an item, but only if we put something inside the brackets. Else, it just gets us the value. So .html() gets the code inside the paragraph, and html(‘new stuff’) changes the content of the paragraph. Bear in mind, if you use .text() or .text(‘hello’) that will just edit the text, but if you wish to add HTML code inside an item, you need to use html().

And if you check out your page, you will find it works! There is one final issue. When viewing a single image, if you hover out, the paragraph goes away. We don’t want this, so we need to go back to our hover function and make a slight edit:

galleryItems.hover(
			function() {
				if($(this).attr('id')!='singleimagedisplay')
				{

					$(this).children("img").next('p').show().attr('id', 'galleryhoverp');
				}

			},
			function() {
				if($(this).attr('id')!='singleimagedisplay')
				{
					$(this).children("img").next('p').hide().attr('id', '');
				}
			}
		);

All we do is see if the id on the item is not set to ‘singleimagedisplay’ which means that we are on the main gallery page, and then we can run the code we had originally. And we are done. You can download everything below:

Download the page and images.

I hope you found this a useful lesson, and I will see you next time.

Jack Franklin

Jack Franklin is a 17 year old budding web designer & developer living in Cornwall, England who enjoys messing with HTML, CSS, PHP & Javascript. Away from the desk, Jack enjoys badminton, football & snooker.

15 Smart Tools To Help You Build Your Freelance Business

Discover the awesome tools we use in making our clients comfortable and happy in learning new things every day.

Download Now

Comments

  1. Dan says

    Hey dude, you need to include links to the previous parts of the tutorial. We shouldn’t have to search around the site to find them. Furthermore, where’s the date on this page? Do you think you guys are outsmarting the Internet by not being dated? Well wake up, JQuery is dated, its next version can be completely different. The Internet is dated and especially web technologies. It only makes you look like sleazebags when you want to try a fool everyone.

    • says

      Hi, no one’s trying to fool anyone. Chill, dude. I’ve updated the article with links to parts 1, 2, and 3. Since you’re interested, this series dates back to August 2010, and I’m also wondering about the dates.

  2. says

    Again another great tutorial. I just have two corrections that have to be made to this. The first one is that you did not add the code to change the size of the parent when the image has been clicked. Also when you are on the large image, if you continue clicking, the word “back” would be added onto the image with each click. just look at the function for the click i have corrected and those bugs should be taken care of. Thanks again, you are helping me a lot with jQuery. keep up the good work. here are the changes:

    // get the image inside the gallery class
    var images = $(‘.galleryitem’).find(‘img’);

    // image is not yet clicked
    var status = 0;

    images.click(
    function()
    {
    // check if image has already been clicked
    if(status === 0)
    {
    // add the id singleimagedisplay to the parent, change its height and hide all the other images
    $(this).parent().attr(‘id’, ‘singleimagedisplay’).css(‘height’, $(this).height()).siblings().hide();

    // set the width of the parent to 800px
    $(this).parent().css(‘width’, ‘800px’);

    // add the ‘back’ text
    $(this).next(‘p’).show().html($(this).next(‘p’).html() + ‘Back’);

    // now it has been clicked, so dont check for clicking on this image anymore
    status = 1;
    }
    })

  3. says

    If one has a slider carousel created with JQery, how does one set the slider to stop moving by default? Is there a parameter one can set?
    Thank you so much,
    Izobella

  4. Mehdi says

    Great tutorial. But i am not sure whether this is the best way to navigate back to the gallery:
    $(this).next(‘p’).show().html($(this).next(‘p’).html() + ‘Back’);
    And the files for this tutorial are still aren’t available for download.
    Anyway, I hope your next tutorial will be something about doing Ajax the Jquery way.

  5. Mike says

    As I understand it the problem with using “jquery/1/jquery.min.js” is that it will never be cached by the browser, thus defeating the object of using the Google CDN. Better to link specifically to the latest version of jQuery.