top of page
  • Writer's pictureDark CSS

Creating a Simple Image Preview with JavaScript: A Beginner's Guide

Introduction:

In this tutorial, we'll walk through the process of creating a simple yet effective image upload preview interface. By the end of this guide, you'll have a basic understanding of how to set up a file upload system and display a preview of the selected image using HTML, CSS, and a touch of JavaScript. We'll start by creating two essential files: index.html to structure our webpage and style.css to style it.

Let's get started!


Image Preview in JavaScript

Html Code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Upload Preview</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <!-- Main container for the content -->
    <div class="container">
        <!-- Header label associated with the file input -->
        <label for="file" class="header">
            <!-- Sub-container for upload interface -->
            <div class="upload-file">
                <!-- Upload icon -->
                <a href="#" id="upload-icon">
                    <ion-icon name="cloud-upload-outline"></ion-icon>
                </a>
                <!-- Text prompting to browse file -->
                <p id="upload-text">Browse File to upload!</p>
            </div>
        </label>
        <!-- Footer label associated with the file input -->
        <label for="file" class="footer">
            <!-- Text indicating no file is selected -->
            <p>Not selected file</p>
        </label>
        <!-- File input element -->
        <input id="file" type="file" accept="image/*" onchange="showPreview(event);">
    </div>
</body>
</html>

Explanation

'<div class="container">: This <div> element acts as a container for the content within the body. It's a common practice to use containers to organize content and apply styling.

<label for="file" class="header">: This <label> element is associated with an input element elsewhere in the code with the ID "file". It's given the class "header" which is likely for styling purposes. Inside this label, there's another <div> element with the class "upload-file", containing an anchor <a> element with the ID "upload-icon" and a paragraph <p> element with the ID "upload-text". This seems to represent an interface for uploading files.

<label for="file" class="footer">: Similar to the previous label, this <label> element is associated with the same input element with the ID "file". It's given the class "footer", possibly indicating its position in the layout. Inside this label, there's a paragraph <p> element which currently displays "Not selected file".

<input id="file" type="file" accept="image/*" onchange="showPreview(event);">: This is an <input> element of type "file", which creates a file upload control. It has an ID of "file", which is referenced by the labels. The attribute accept="image/*" specifies that the user can only select image files. The onchange attribute specifies a JavaScript function showPreview(event); to be executed when the file selection changes. This function is typically used to display a preview of the selected image.



CSS Code:

/* Importing Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');

/* Global reset and font setup */
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

/* Grid setup for centering content */
html,body {
    display: grid;
    height: 100%;
    place-items: center;
    background: #e2e5e6;
}

/* Styling for the main container */
.container {
    height: 300px;
    width: 300px;
    border-radius: 10px;
    box-shadow: 4px 4px 30px rgba(0, 0, 0, .2);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    gap: 5px;
    background-color: rgba(0, 110, 255, 0.041);
}

/* Styling for the header section */
.header {
    flex: 1;
    width: 100%;
    border: 2px dashed royalblue;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    background-position: center;
    background-size: cover;
}

/* Styling for the upload file section */
.upload-file {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}

/* Styling for the upload icon */
.upload-file a {
    font-size: 100px;
    color: #000;
}

/* Styling for the upload text */
.upload-file p {
    text-align: center;
    color: rgb(41, 40, 40);
    font-weight: 400;
    font-size: 18px;
    margin-top: -40px;
}

/* Styling for the footer section */
.footer {
    background-color: rgba(0, 110, 255, 0.075);
    width: 100%;
    height: 40px;
    padding: 8px;
    border-radius: 10px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: black;
    border: none;
}

/* Styling for the footer text */
.footer p {
    flex: 1;
    text-align: center;
}

/* Hiding the file input element */
#file {
    display: none;
}
Explanation

The @import rule is used to import the Google Fonts stylesheet for the 'Poppins' font. The * selector applies a global reset by removing padding and margin and setting box-sizing to border-box for all elements. It also sets the font family to 'Poppins'. The html,body selector applies grid display to center content vertically and horizontally, with a background color of #e2e5e6. The .container class styles the main container with a fixed height, width, border radius, box shadow, flexbox properties, padding, gap, and background color. The .header class styles the header section with flexbox properties, border, and background. The .upload-file class styles the upload file section with flexbox properties. The .upload-file a and .upload-file p classes style the upload icon and text, respectively. The .footer class styles the footer section with flexbox properties, background color, padding, border radius, cursor, and color. The #file selector hides the file input element.

This CSS code creates a visually appealing and responsive layout for the image upload preview interface.


JavaScript Code
<script>
    // Function to show preview of the selected image
    function showPreview(event) {
        // Get the file input element
        const fileInput = event.target;
        // Get the selected file
        const file = fileInput.files[0];
        // Select relevant DOM elements
        const header = document.querySelector('.header');
        const uploadIcon = document.getElementById('upload-icon');
        const uploadText = document.getElementById('upload-text');
        const footer = document.querySelector('.footer');

        // If a file is selected
        if (file) {
            // Create a FileReader object
            const reader = new FileReader();
            // Define onload event handler
            reader.onload = function (e) {
                // Set background image of header to the uploaded image
                header.style.backgroundImage = `url(${e.target.result})`;
                // Remove border and hide upload icon and text
                header.style.border = 'none';
                uploadIcon.style.display = 'none';
                uploadText.style.display = 'none';
                // Display file name in footer
                footer.innerHTML = `<p>${file.name}</p>`;
            };
            // Read the file as a data URL
            reader.readAsDataURL(file);
        } else { // If no file is selected
            // Reset header background, show upload icon and text, reset border, and display default footer text
            header.style.backgroundImage = 'none';
            uploadIcon.style.display = 'inline';
            uploadText.style.display = 'block';
            header.style.border = '2px dashed royalblue';
            footer.innerHTML = `<p>Not selected file</p>`;
        }
    }
</script>

Explanation

  • The showPreview function is triggered when a file is selected using the file input element.

  • It retrieves the selected file using event.target.files[0].

  • It then selects relevant DOM elements using document.querySelector and document.getElementById.

  • Inside the function:

  • If a file is selected, a FileReader object is created to read the file.

  • When the file is loaded (reader.onload), the background image of the header is set to the uploaded image using the data URL.

  • The upload icon and text are hidden, and the file name is displayed in the footer.

  • If no file is selected, the header background is reset, the upload icon and text are shown, and the default footer text is displayed.

  • The function updates the DOM elements accordingly to reflect the selected file and its preview.

This JavaScript code provides functionality to display a preview of the selected image and update the interface dynamically based on user input.


Conclusion

In conclusion, we've successfully developed a straightforward image preview project using HTML, CSS, and JavaScript. This project enables users to select an image file and instantly preview it within the interface, enhancing the user experience. By combining these fundamental web technologies, we've created a functional and intuitive solution that can be further expanded and customized to meet specific requirements. This project highlights the power of HTML for structure, CSS for styling, and JavaScript for interactivity, providing a solid foundation for future web development endeavors.


Download Source Code:


Image Perview
.zip
Download ZIP • 2KB

Related Posts

See All

Dark CSS

bottom of page