Image Preview using HTML, Bootstrap, and jQuery

Posted on

How to make a Live image preview?

Uploading files, especially images, is a common feature in modern web applications. Providing users with a preview of the selected image enhances the user experience by letting them verify their selection before submitting the form. In this article, we will explore how to implement a live image preview using HTML, Bootstrap, and jQuery.

The Goal

We want to create a responsive input form where:

  1. A placeholder image is shown by default.
  2. When the user selects an image, it will replace the placeholder with the selected image preview.
  3. If no image is selected, the placeholder will remain.
Image Preview using HTML, Bootstrap, and jQuery
Example of the goal

Technologies Used

  • HTML: For structuring the layout.
  • Bootstrap: For styling and responsiveness.
  • jQuery: To simplify the process of reading and displaying the image.

Code Implementation

Here’s the complete code to achieve this functionality:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Preview Example</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .img-thumbnail {
            max-width: 150px;
            max-height: 150px;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-4 text-center">
                <div class="mb-3">
                    <!-- Placeholder for image preview -->
                    <img id="previewImage" src="https://via.placeholder.com/150" alt="Preview Gambar"
                        class="img-thumbnail mb-3">
                    <!-- Input for file upload -->
                    <input type="file" class="form-control" id="supirPhoto" name="supirPhoto" accept="image/*">
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery and Bootstrap Bundle -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function () {
            // Function to handle the image preview
            $('#supirPhoto').on('change', function () {
                const file = this.files[0]; // Get the first selected file
                const previewImage = $('#previewImage');

                if (file) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        previewImage.attr('src', e.target.result); // Update the src attribute
                    };
                    reader.readAsDataURL(file); // Read the file as a Data URL
                } else {
                    // If no file is selected, reset to the placeholder image
                    previewImage.attr('src', 'https://via.placeholder.com/150');
                }
            });
        });
    </script>
</body>
</html>

Below is an example of the results of the program code above. You can try uploading an image using the button below, after that the image will appear automatically. Image Preview Example

Preview Gambar

How It Works

HTML Structure

  • <img> Element: Displays the placeholder image. The id="previewImage" lets us target it via jQuery to update its src attribute dynamically.
  • <input> Element: A file input with the accept="image/*" attribute restricts users to only select image files.

Styling with Bootstrap

  • The form-control class is applied to the file input for consistent styling.
  • The img-thumbnail class ensures that the preview image has a bordered thumbnail look.

Using jQuery

  1. File Selection Detection:
    • The on('change') event detects when a file is selected in the input field.
  2. Reading the File:
    • The FileReader API reads the selected file as a Data URL.
  3. Updating the Preview:
    • The attr() method updates the src attribute of the <img> element with the file’s Data URL.

Fallback Mechanism

If no file is selected, the placeholder (https://via.placeholder.com/150) is restored as the default image.