Search code examples
javascriptfunctionrepeat

running function continuously in javascript


im trying to change the title to the text input whenever there is a keypress, sometimes it doesn't register a keypress so i need to update it every second but when i have it run the function it just doesn't do anything here is my code.

    <input type="text" id="title" size="150" onkeypress="changePageTitle()">
<html>

<head>
  <title>
    please choose title
  </title>
</head>

<body>
  <br>
  <button onclick="changePageTitle()">
    Change Page Title
  </button>

  <script type="text/javascript">
    function changePageTitle() {
      newPageTitle = document.getElementById('title').value;
      document.title = newPageTitle;
    }
const interval = setInterval(function() {
function changePageTitle()
 }, 1000);
  </script>
</body>

</html>

also, I don't know how to use jquery or any other extensions so please try to keep it just normal javascript


Solution

  • You need to put your <input> inside the body.
    You need to actually call the changePageTitle() function.

    <html>
    
    <head>
      <title>
        please choose title
      </title>
    </head>
    
    <body>
        <input type="text" id="title" size="150" onkeypress="changePageTitle()">
      <br>
      <button onclick="changePageTitle()">
        Change Page Title
      </button>
    
      <script type="text/javascript">
        function changePageTitle() {
          newPageTitle = document.getElementById('title').value;
          document.title = newPageTitle;
        }
    const interval = setInterval(function(){
      changePageTitle()
    }, 1000);
      </script>
    </body>
    
    </html>