jQuery Image Pop-over on Click
Let's Make a Simple jQuery Pop-up Overlay
This code is written to be applied to any images on your site pages. You can target by specific class, or by using descending selectors to capture all images inside a certain containing div. Let's take a look at a basic webpage:
You can see that there are multiple images throughout the page in different sections. Even images in the header, such as the site logo, and the footer. Our goal is to target the smaller grid images in the main column of the page.
Targeting the Right Images
Let's look at the structure of our webpage:
You can see that the main structure revolves around three main divs: #header, #main-col, and #sidebar. You can also see that the images we want are in the '#main-col' div. If we were to write our jQuery selector to be $(#main-col img); this would affect all images in the #main-col div, even the header image, so we will need to make sure the images we want to target all have the same class, or are placed inside a unique containing div wrapper. Let's say that they are wrapped in a div with the class 'product-images', our jQuery target elemt would then be $('#main-col .product-images img');. Now we are targeting only the images we want for our click event.
The jQuery Image Pop-up Overlay
Here's what we want it to look like when we click on an image on the webpage:
The image we have clicked on now appears larger on screen, and has a nice darkened overlay behind it.
What we are doing is using jQuery to append the overlay markup to the 'body' which contains an image tag. On the click event, we are grabbing the 'src' of the image we clicked on and setting it as a variable that we then inject into the image tag in the overlay markup. Each time you click on an image, the 'src' in the overlay image tag is changed showing the correct image. Inside the same click event we are also showing and hiding the overlay itself, as well as stoping the document body from scrolling to maintain position.
Below you will find the code in a nice little Fiddle. The only sections that need to be copied are the jQuery and the CSS. In the jQuery you will see the first variable being set is 'var productImage'. Update the 'img' part of $('img'); to be '.whatever .your .selectors .are' to make it all work!