WP-Mix

A fresh mix of code snippets and tutorials

jQuery Preview Selected Images

This jQuery script displays a live preview of the currently selected images, as selected from a file input field.

Given the following markup:

<input type="file" id="multiple-files">
<div class="image-preview"></div>

We can apply the following jQuery to display a preview of the selected images:

var inputLocalFiles = document.getElementById("multiple-files");
inputLocalFiles.addEventListener("change", previewImages, false);
function previewImages() {
	$('.image-preview').empty();
	var fileList = this.files;
	var anyWindow = window.URL || window.webkitURL;
	for (var i = 0; i < fileList.length; i++) {
		var j = i + 1;
		var objectUrl = anyWindow.createObjectURL(fileList[i]);
		$('.image-preview').append('<div class="image-preview-' + j + '"><a href="' + objectUrl + '" title="Preview of image #' + j + '"></a></div>');
		$('.image-preview-' + j).css({ 'background-image' : 'url(' + objectUrl + ')', 'background-size' : 'cover', 'background-repeat' : 'no-repeat', 'background-position' : 'center center' });
		window.URL.revokeObjectURL(fileList[i]);
	}
}

This snippet basically detects when the input field has selected files, and if so uses them as background-images for <div>s appended to the .image-preview <div>.

No editing to the code is required, but the markup provided in the example is rather basic, and should be fleshed out with complete form structure or whatever is required for your design.

★ Pro Tip:

SES Pro