Dynamic Title Example

This is an example from the HTML Elements page.


Type in the new title

When you type something in the box and click on the button the page title will update.







Sample Code

Here's a sample of the code used:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Title</title>
</head>
<body>
    <h1>Enter a New Title</h1>
    <input type="text" id="titleInput" placeholder="Type a new title" aria-label="Enter a new title" required>
    <button id="updateTitleButton" aria-label="Update the page title">Update Title</button>

    <script>
        const input = document.getElementById('titleInput');
        const button = document.getElementById('updateTitleButton');

        // Function to sanitize input
        function sanitizeInput(input) {
            const div = document.createElement('div');
            div.textContent = input; // Escapes special characters
            return div.textContent;
        }

        // Function to validate input
        function isValidTitle(input) {
            const regex = /^[a-zA-Z0-9\s]+$/; // Only letters, numbers, and spaces
            return regex.test(input);
        }

        // Function to update the title
        function updateTitle() {
            const newTitle = sanitizeInput(input.value.trim());
            if (newTitle && newTitle.length <= 60 && isValidTitle(newTitle)) {
                document.title = newTitle;
                alert(`Title updated to: "${newTitle}"`);
            } else if (newTitle.length > 60) {
                alert("Title is too long. Please keep it under 60 characters.");
            } else {
                alert("Invalid title. Please use only letters, numbers, and spaces.");
            }
        }

        // Add click event listener to the button
        button.addEventListener('click', updateTitle);

        // Add keypress event listener to the input field for "Enter" key
        input.addEventListener('keypress', (event) => {
            if (event.key === 'Enter') {
                updateTitle();
            }
        });
    </script>
</body>
</html>