Useful jQuery Code Snippets for Working with Images
Images are an essential part of any website and sometimes working with images for various functionalities can be quite challenging. However, if you know where to look you will often find that the feature you are trying to implement has already been created by someone else and is available for reuse. This post provides a list of useful jQuery code snippets for working with images. These code snippets cover functionalities like changing the images on mouse over, checking image resolution before uploading the image, getting the loaded image status, validating the external image URL, zooming an image inside its container, displaying a caption on top of an image and several other tasks. Check it out!
- Changing or swapping the image on mouse over
The following code will change/swap the image on mouse over and restore the original on mouse out event. It makes use of the hover() event which is a combination of mouse enter and mouse leave event. The hover event binds two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. The first handler is for mouse enter event and the second handler is for mouse leave.
$(document).ready(function(){ $("#imgHome").hover(function(){ $(this).attr('src','/img/home-icon-full.png'); }, function(){ $(this).attr('src','/img/home-icon.png'); }); });
The above code will set the source of image to the home-icon-full.png in the first handler and when the mouse moves out it updates the source of image to home-icon.png.
- Check image resolution before uploading
Sometimes you may wish to validate the image resolution before actually uploading an image to the server. This is quite useful when you only allow a certain resolution image to be uploaded. One way is to actually upload the image and then check the resolution, but that would not be an ideal solution as it makes a server side call. The perfect solution would be to check the resolution on the client side before uploading the image to avoid the server call. To implement this, we need to use the checkImageSize jQuery plugin. This plugin is for file input that allows you to validate the required image resolution (min/max height and width) before uploading. To use it, download the library and include the reference with the jQuery library. Then call the function checkImageSize() on the desired file input:
$(document).ready(function(){ $("input[type=file]").checkImageSize(); });
You can define the expected image resolution either on the file input control or via plugin options:
<input type="file" data-min-width="800" data-min-height="600" data-max-width="8000" data-max-height="6000" >
Or
$("input[type=file]").checkImageSize({ minWidth: 800, minHeight: 600, maxWidth: 8000, maxHeight: 6000, showError: true, // Flag to show error messages. ignoreError: false // Flag to ignore error and let the image pass. });
This plugin creates an image object in the memory and loads it to verify the image resolution. If it doesn’t match with the user specified resolution, it throws an error. If you don’t specify any resolution options, the default values will be used. The above jQuery code shows the options and their default values.
- Get image loading status
A website may have many images placed on different web pages. Over a period of time, image counts increase as you keep on adding new images to the website. Then it becomes really difficult to identify whether every single image on every web page is getting loaded properly or not. Image loading may fail for many reasons, for example if the image location is changed, the image name is changed or the image is no longer available. In such a scenario, it would be pretty useful to have a script which can tell us how many images are getting loaded properly and how many are failing.
jQuery doesn’t have any such feature out of the box, but there is a jQuery plugin called imagesStatus that is worth considering. This is an image loading detection plugin that allows you to check whether an image is loaded successfully. This plugin provides callback functions for image status. To use this plugin, download the library and include the reference with the jQuery library. Then attach the imagesStatus() function to the HTML body tag to learn the status of every single image present on that web page. Like this:
$("body").imagesStatus({ imgLoaded: function(img){ console.log(this.status.loaded); console.log(img); }, imgFailed: function(img){ console.log(this.status.failed); console.log("-------failed---------------"); console.log(img); console.log("-----------------------------"); }, allImgFinished: function(container){ console.log(this.status.loaded + " images loaded, " + this.status.failed + " images failed!"); } });
Here imgLoaded, imgFailed and allImgFinshied are 3 different callbacks. As the name suggest, it is easy to understand their purpose. This will log all the details about image statuses in the browser console window, which is very useful for troubleshooting errors.
Instead of the complete page, if a particular section of the web page needs to be checked, then attach this function to that container. As an example, if the div element with ID imageContainerDiv holds images and you want to check the status of only the images that are part of this particular div element, attach the function to the div. Like this:
$("#imageContainerDiv").imagesStatus({
In case of image loading failing, you can utilize the imgFailed callback function and put code to send an email to someone on your team or store this information in a file to log which images are failing.
- Zoom-in an image within its container
Image zooming is a common functionality which you will find on many websites, especially ecommerce websites. Implementing this functionality is also very easy due to high availability of zoom image jQuery plugins. But it is challenging to zoom an image within the container as the zoomed image should not overlap or come out of the container. It has to zoom in and zoom out inside the container. Let’s take a look at how to do it. First, consider the following HTML where the image is part of a container:
<div class="container"> <img src="imgDemo.png" /> </div>
The following CSS classes will be used to style the container and the image:
.container { width: 400px; height: 400px; margin: auto; position: relative; overflow: hidden; } img { width: 400px; height: 400px; position: absolute; top: 0; left: 0; }
The following jQuery code will implement the zoom-in and zoom-out image on hover:
$('img').hover(function() { $(this).animate({ 'width': '600px', 'height': '600px', 'top': '-100px', 'left': '-100px' }, 300); }, function() { $(this).animate({ 'width': '400px', 'height': '400px', 'top': '0px', 'left': '0px' }, 300); });
The above jQuery code uses animate method to change the CSS properties width, height, top and left to create a zoom-in effect on mouse over event and restoration back to its original state on mouse out event. You can check out the demo at the following link!
- Update all images extensions
Imagine a situation where your website currently features some images in PNG format and for some reason the format is updated to JPEG. With this change all the PNG image links would be broken and they would not appear on the webpage. Manually updating the image extensions of all your PNG images to JPEG in the code would be a nightmare. But jQuery can help here to save you from this nightmare. The following jQuery code will update the extension of PNG images to JPEG. It loops through all the images with .png extensions and then simply replaces the extension with .jpg.
$(document).ready(function() { $('img[src$=".png"]').each(function(index, element) { element.src = element.src.replace('.png,'.jpg); }); });
});
You don’t have to put this script on every single page. Instead, put this script in a JavaScript file and save it. Then include the reference to the saved file in all your pages and script will take care of replacing the .png images extensions with .jpg.
- Change image opacity on mouse over
The following jQuery code snippet shows how to change the opacity of any image on mouse over and restore it again on mouse out. Opacity is the degree of image transparency. The opacity property can take a value from 0.0 - 1.0. The lower the value, the more transparent the image will be.
$(document).ready(function() { $("img").hover(function() { $(this).animate({ opacity: 0.4 }, 300); }, function() { $(this).animate({ opacity: 1.0 }, 300); }); });
In the hover() event, change the image opacity to 0.4 in the first handler, and in the second handler update it again to 1. You can check out the demo at the following link!
- Display caption on an image on mouse over event
The following jQuery code snippet allows you to display a caption on an image on mouse over event. The solution would add a dynamic layer to display the caption on top of the image. This layer would appear on mouse over and the caption would be picked from the alt attribute of the image.
Let’s implement this!
First, take a look at the following HTML where there are 4 images placed in an unordered list. Don’t forget to include the alt attributes for the images.
<ul> <li><img src="https://placehold.it/150x150/00aef0/ffffff" alt="Color code is 00aef0" /></li> <li><img src="https://placehold.it/150x150/00bdf0/ffffff" alt="Color code is 00bdf0" /></li> <li><img src="https://placehold.it/150x150/00cdf0/ffffff" alt="Color code is 00cdf0" /></li> <li><img src="https://placehold.it/150x150/00ddf0/ffffff" alt="Color code is 00ddf0" /></li> </ul>
The following CSS classes will be used to style the image positions and also hold the CSS class for the caption element. The CSS class .caption would be used to style the dynamic layer which will appear on top of the image.
li { float: left; margin: 10px; display: block; position: relative } .caption { position: absolute; background: RGBA(255, 255, 255, 0.4); top: 0; right: 0; font: 12pt calibri; color: black; text-align: center; line-height: 100px; width: 150px; height: 150px; display: none; }
The following jQuery code attaches the hover() event to li tag. In the first handler of the hover event,
- Set the mouse pointer to cursor.
- Get the caption text from the alt attribute of the image and store it in a variable. Since the hover event is attach to li element, use find method to get the image element.
- Create a div element with caption class and add the text (stored in the variable). Append this to the li element so that it becomes part of the DOM.
- Finally, display the newly attached div element using fadeIn() method.
In the second handler, which gets called on mouse out, find the newly attached div and using fadeout() method remove it from the DOM:
$(document).ready(function() { $("li").hover( function() { $(this).css("cursor", "pointer"); var hoverText = $(this).find('img').attr('alt'); $(this).append($("<div class='caption'>" + hoverText + "</div>")); $(this).find(".caption").fadeIn(); }, function() { $(this).find(".caption").fadeOut(function() { $(this).remove(); }) }); });
You can check out the demo at the following link!
- Verify if external image URL is valid or not
If your website is using external or third party URLs for displaying images, then it is ideal to first verify the URLs. This is important because there could be an invalid URL and in that case the image would not load at all. The following jQuery code snippets will validate the external image URLs. It defines a function which accepts the external image URL and checks the validity. jQuery provides an error event which is called when the element is not loaded properly. This function creates an image element and sets the external URL as the source. If the URL is not valid, an error event will be called, otherwise load will be called.
function IsValidImageUrl(imgURL) { $("", { src: imgURL, error: function() { console.log(imgURL + ': ' + false); }, load: function() { console.log(imgURL + ': ' + true); } }); }
If you wish to display an image preview of the external image on the website, then place an image element and assign the URL as the source to image element as soon as a URL is in the input box. The following jQuery code snippet actually does the exact job for you:
$(document).ready(function() { $('#txtURL').change(function() { $('#imgPreview').attr('src', $('#txtURL').val()); }) });
Conclusion
To sum it up, these jQuery code snippets for handling and controlling the image elements are super handy and useful. These snippets can make your life simpler and save you time. They offer solutions for various functionalities like changing or swapping the images on mouse over, changing the image opacity, updating the image’s extension, validating the external or third party URL for images, zooming-in an image inside its container and displaying captions on image mouse over.