DEV Community

Ben Santora
Ben Santora

Posted on

Simple Image Viewer in JavaScript

This is a very simple image viewer that runs in the web browser. It uses a single .html file and 36 lines of code. Save the code as index.html - clicking on this file will open a window in your browser allowing you to choose an image from your pc to display. I've been able to open a 1024 x 1024 image - nice.

Here's the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Image Viewer</title>
    <style>
        body {
            background-color: #f0f0f0;
            text-align: center;
            font-family: Arial, sans-serif;
        }
        img {
            max-width: 100%;
            height: auto;
            border: 2px solid #000;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <h1>Simple Image Viewer</h1>
    <input type="file" id="fileInput" accept="image/*">
    <img id="imageViewer" src="#" alt="Your image will appear here.">
    <script>
        const fileInput = document.getElementById('fileInput');
        const imageViewer = document.getElementById('imageViewer');

        fileInput.addEventListener('change', function() {
            const file = this.files[0];
            const url = URL.createObjectURL(file);
            imageViewer.src = url;
        });
    </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Ben Santora - October 2024

Top comments (0)