Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript how to change page title with user input

The thing i wanna do is when user writes something to input and sumbits it, the page will change to the input.

Example:

If user writes "Web" to the input, the page title should change to "Web"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s the code:

JS:

document.getElementById("titleSumbitBtn").onclick = function (){
    var newTitle = document.getElementById("newTitle").textContent;
    document.getElementById("title").innerHTML = newTitle;
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title id="title">Web Editor</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <center><label id="originLabel">Welcome to Web Editor!</label><br></center>
    <br><label id="changeTitleLabel">Change the title of Web: </label><br>
    <input type="text" id="newTitle"><br>
    <button type="button" id="titleSumbitBtn">Change</button>
</body>
</html>

>Solution :

You can assign new title to the document like this:

document.getElementById("titleSumbitBtn").onclick = function (){
    var newTitle = document.getElementById("newTitle").value;
    document.title = newTitle;
}

This is actual implementation but keep in mind that it must run after the DOM element with id newTitle.

If you put your <script> tag inside <head>, you’ll need DOMContentLoaded:

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById("titleSumbitBtn").onclick = function (){
        var newTitle = document.getElementById("newTitle").value;
        document.title = newTitle;
    }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading