Skip to content

Instantly share code, notes, and snippets.

@simonw
Created September 20, 2024 04:03
Show Gist options
  • Save simonw/c85653221e4933d5b7950a5971eb3380 to your computer and use it in GitHub Desktop.
Save simonw/c85653221e4933d5b7950a5971eb3380 to your computer and use it in GitHub Desktop.

Populate Input from URL Param

human (Sep 19, 2024, 09:01 PM)

Set it up so that if the page is loaded with ?url=XXX then that is treated as if it was entered in the box, and the box is populated with that

Any time the input is modified the URL should be updated to reflect the new contents of that input

assistant (Sep 19, 2024, 09:01 PM)

Certainly, I can help you modify the code to implement those features. I'll update the HTML and JavaScript to handle URL parameters and keep the URL in sync with the input box. Here's the modified version:

YouTube Thumbnail Viewer with URL Sync

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YouTube Thumbnail Viewer</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            max-width: 800px;
            margin: 0 auto;
            padding: 1em;
        }
        input {
            width: 100%;
            padding: 10px;
            font-size: 18px;
            margin-bottom: 20px;
            box-sizing: border-box;
        }
        .thumbnail-container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .thumbnail {
            text-align: center;
        }
        .thumbnail img {
            max-width: 90%;
            width: auto;
            height: auto;
            border: 1px solid #ddd;
            padding: 5px;
            transition: max-width 0.3s ease;
        }
        .thumbnail img.expanded {
            max-width: none;
        }
        .thumbnail p {
            margin-top: 5px;
            font-size: 14px;
            word-break: break-all;
        }
        .thumbnail-url {
            background-color: #f9f9f9;
            padding: 5px;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        .copy-icon {
            margin-right: 10px;
        }
    </style>
</head>
<body>

    <h1>YouTube Thumbnail Viewer</h1>
    <p>Enter a YouTube URL or Video ID:</p>
    <input type="text" id="videoInput" placeholder="Paste YouTube URL or video ID here" oninput="updateThumbnails()">

    <div id="thumbnails" class="thumbnail-container"></div>

    <script>
        function extractVideoID(url) {
            const regex = /(?:https?:\/\/(?:www\.)?youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|embed)\/|.*[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
            const match = url.match(regex);
            return match ? match[1] : url;
        }

        function updateThumbnails() {
            const input = document.getElementById("videoInput").value.trim();
            const videoID = extractVideoID(input);
            if (videoID.length === 11) {
                const imageTypes = ['default', 'hqdefault', 'mqdefault', 'sddefault', 'maxresdefault', '0', '1', '2', '3'];
                const container = document.getElementById("thumbnails");
                container.innerHTML = '';

                imageTypes.forEach(type => {
                    const imageUrl = `https://img.youtube.com/vi/${videoID}/${type}.jpg`;
                    const thumbnailHTML = `
                        <div class="thumbnail">
                            <img src="${imageUrl}" alt="Thumbnail ${type}" onclick="toggleExpand(this)">
                            <p class="image-size"></p>
                            <div class="thumbnail-url" onclick="copyText('${imageUrl}')">
                                <span class="copy-icon">📋</span>
                                <span>${imageUrl}</span>
                            </div>
                        </div>
                    `;
                    container.innerHTML += thumbnailHTML;
                });

                // Get actual image sizes after they've loaded
                document.querySelectorAll('.thumbnail img').forEach(img => {
                    img.onload = function() {
                        this.nextElementSibling.textContent = `Width: ${this.naturalWidth}px`;
                    }
                });

                // Update URL
                updateURL(input);
            }
        }

        function toggleExpand(img) {
            img.classList.toggle('expanded');
        }

        function copyText(text) {
            navigator.clipboard.writeText(text).then(() => {
                console.log('Copied to clipboard');
            }).catch(err => {
                console.error('Failed to copy: ', err);
            });
        }

        function updateURL(input) {
            const url = new URL(window.location);
            url.searchParams.set('url', input);
            window.history.pushState({}, '', url);
        }

        function loadFromURL() {
            const urlParams = new URLSearchParams(window.location.search);
            const urlValue = urlParams.get('url');
            if (urlValue) {
                document.getElementById("videoInput").value = urlValue;
                updateThumbnails();
            }
        }

        // Call loadFromURL when the page loads
        window.onload = loadFromURL;
    </script>

</body>
</html>

I've made the following changes to the code:

  1. Added a loadFromURL() function that checks for a url parameter in the page URL when the page loads. If present, it populates the input box with this value and triggers the thumbnail update.

  2. Added a call to window.onload = loadFromURL; to ensure the loadFromURL() function runs when the page loads.

  3. Created an updateURL(input) function that updates the page URL with the current input value whenever the input changes.

  4. Modified the updateThumbnails() function to call updateURL(input) whenever the thumbnails are updated.

These changes will allow the page to load with a pre-filled URL parameter and keep the URL in sync with the input box contents. Users can now share links with specific YouTube videos pre-loaded, and the current state of the input will be reflected in the URL for easy sharing or bookmarking.

To test this, you can now load the page with a URL like index.html?url=https://www.youtube.com/watch?v=dQw4w9WgXcQ, and it will automatically populate the input and display the thumbnails. As you modify the input, the URL will update accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment