Summary

Learn how to create a responsive screen size tester tool with HTML, CSS, and JavaScript. Test websites at different device sizes with this customizable solution.

Article Body

How to Build a Responsive Screen Size Tester Tool - Step-by-Step Guide
How to Build a Responsive Screen Size Tester Tool - Step-by-Step Guide

Step-by-Step Guide to Create a Responsive Screen Size Tester

1. Set Up the HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Screen Size Tester</title>
    <!-- We'll add CSS and JS includes here -->
</head>
<body>
    <!-- Main content will go here -->
</body>
</html>

2. Add CSS Styling

Include Tailwind CSS and Font Awesome, then add custom styles:

<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    .resize-handle {
        width: 10px;
        height: 10px;
        background: #3b82f6;
        position: absolute;
        right: -5px;
        bottom: -5px;
        cursor: nwse-resize;
        border-radius: 50%;
        border: 2px solid white;
    }
    .device-frame {
        box-shadow: 0 0 0 12px #1e293b, 0 0 24px rgba(0, 0, 0, 0.3);
    }
    #viewport-container {
        transition: width 0.2s ease, height 0.2s ease;
    }
</style>

3. Create the Controls Panel

<div class="lg:col-span-1 bg-gray-800 rounded-xl p-6 space-y-6">
    <!-- Device Presets -->
    <div>
        <h2 class="text-xl font-semibold mb-4">Device Presets</h2>
        <div class="grid grid-cols-2 gap-3">
            <button data-width="360" data-height="640" class="device-btn px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg text-sm flex items-center">
                <i class="fas fa-mobile-alt mr-2"></i> Mobile
            </button>
            <!-- Add other device buttons -->
        </div>
    </div>
    
    <!-- Custom Size Inputs -->
    <div>
        <h2 class="text-xl font-semibold mb-4">Custom Size</h2>
        <div class="space-y-4">
            <div>
                <label for="width-input" class="block text-sm font-medium mb-1">Width (px)</label>
                <input type="number" id="width-input" min="100" max="5000" value="1024" class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg">
            </div>
            <!-- Height input and apply button -->
        </div>
    </div>
    
    <!-- Options and URL input -->
</div>

4. Build the Viewport Area

<div class="lg:col-span-3">
    <div class="flex justify-between items-center mb-4">
        <div id="dimensions-display" class="text-lg font-mono bg-gray-800 px-3 py-1 rounded-lg">
            1024 × 768 px
        </div>
        <div class="flex space-x-2">
            <button id="rotate-btn" class="p-2 bg-gray-800 hover:bg-gray-700 rounded-lg">
                <i class="fas fa-undo"></i> Rotate
            </button>
            <!-- Fullscreen button -->
        </div>
    </div>

    <div class="relative flex items-center justify-center bg-gray-800 rounded-xl p-4 min-h-[400px]">
        <div id="viewport-container" class="relative bg-white device-frame">
            <iframe id="test-iframe" src="about:blank" frameborder="0" class="w-full h-full"></iframe>
            <div class="resize-handle"></div>
        </div>
    </div>
</div>

5. Add JavaScript Functionality

document.addEventListener('DOMContentLoaded', function() {
    // Get all DOM elements
    const iframe = document.getElementById('test-iframe');
    const viewportContainer = document.getElementById('viewport-container');
    // ... (get other elements as shown in the original code)

    // Set initial size
    updateViewportSize(1024, 768);

    // Device preset buttons event listeners
    deviceBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const width = parseInt(this.getAttribute('data-width'));
            const height = parseInt(this.getAttribute('data-height'));
            updateViewportSize(width, height);
            widthInput.value = width;
            heightInput.value = height;
        });
    });

    // Custom size application
    applySizeBtn.addEventListener('click', function() {
        const width = parseInt(widthInput.value);
        const height = parseInt(heightInput.value);
        if (width >= 100 && height >= 100) {
            updateViewportSize(width, height);
        }
    });

    // ... (add all other event listeners as in the original code)

    function updateViewportSize(width, height) {
        viewportContainer.style.width = `${width}px`;
        viewportContainer.style.height = `${height}px`;
        dimensionsDisplay.textContent = `${width} × ${height} px`;
        
        iframe.style.width = `${width}px`;
        iframe.style.height = `${height}px`;
    }

    // Load a default page
    iframe.src = 'https://example.com';
});

6. Implement Resizing Functionality

// Resize handle events
resizeHandle.addEventListener('mousedown', function(e) {
    if (!resizableCheckbox.checked) return;
    
    e.preventDefault();
    isResizing = true;
    startX = e.clientX;
    startY = e.clientY;
    startWidth = parseInt(document.defaultView.getComputedStyle(viewportContainer).width, 10);
    startHeight = parseInt(document.defaultView.getComputedStyle(viewportContainer).height, 10);
    
    document.documentElement.addEventListener('mousemove', handleResize);
    document.documentElement.addEventListener('mouseup', stopResize);
});

function handleResize(e) {
    if (!isResizing) return;
    
    const newWidth = startWidth + e.clientX - startX;
    const newHeight = startHeight + e.clientY - startY;
    
    // Minimum size constraints
    const minSize = 100;
    const constrainedWidth = Math.max(minSize, newWidth);
    const constrainedHeight = Math.max(minSize, newHeight);
    
    updateViewportSize(constrainedWidth, constrainedHeight);
    widthInput.value = constrainedWidth;
    heightInput.value = constrainedHeight;
}

function stopResize() {
    isResizing = false;
    document.documentElement.removeEventListener('mousemove', handleResize);
    document.documentElement.removeEventListener('mouseup', stopResize);
}

7. Add URL Loading and Other Features

// Load URL
loadUrlBtn.addEventListener('click', function() {
    const url = testUrlInput.value.trim();
    if (url) {
        try {
            if (!url.startsWith('http://') && !url.startsWith('https://')) {
                iframe.src = 'https://' + url;
            } else {
                iframe.src = url;
            }
        } catch (e) {
            console.error('Error loading URL:', e);
        }
    }
});

// Rotate viewport
rotateBtn.addEventListener('click', function() {
    isRotated = !isRotated;
    const currentWidth = parseInt(widthInput.value);
    const currentHeight = parseInt(heightInput.value);
    widthInput.value = currentHeight;
    heightInput.value = currentWidth;
    updateViewportSize(currentHeight, currentWidth);
});

// Fullscreen mode
fullscreenBtn.addEventListener('click', function() {
    if (document.fullscreenElement) {
        document.exitFullscreen();
    } else {
        viewportContainer.requestFullscreen().catch(err => {
            console.error('Error attempting to enable fullscreen:', err);
        });
    }
});

 

TOPICS MENTIONED IN THIS ARTICLE

About the Author(s)

  • ttimesnow photo

    ttimesnow

    ttimesnow – Author, Curator, and Analyst at [ttimesnow]

    ttimesnow is an experienced journalist with a passion for uncovering the latest trends and breaking news in technology, politics, and culture. ttimesnow combines deep research with a unique perspective to deliver insightful, well-rounded articles that keep readers informed and engaged. At [ttimesnow], ttimesnow curates daily content that brings the world’s most relevant news right to your fingertips.

    View all articles by ttimesnow