Freddy Bausley Freddy Bausley - 2 months ago 5
Javascript Question

How to use external Javascript to use onclick event to change document.title?

This code runs immediately once the page is loaded. The onclick event is completely ignored by javascript. What is an easy fix for this because like youtube when you play a video the document.title is updated with a speaker. I want to learn to do that with external javascript because I can do it with internal javascript in the html.

<!DOCTYPE html>
<html>
<head>
<title> Animation </title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="animationcss.css">
</head>
<body>

<script src="animation.js"></script>



<input id="changeButton" type="button" value="Change" ></input>





/External Javascript/

var element = document.getElementById("changeButton");
element.onclick = textChange("changetothis");

function textChange(text){
document.title = text;


}

Answer

try calling the function after the document is loaded by placing the script tag below the object or making $(document).ready() function, this code works fine with me

  <!DOCTYPE html>
  <html>
  <head>
  <title> Animation </title>
  <meta charset="UTF-8">
  </head>
  <body>
  <input id="changeButton" type="button" value="Change" ></input>
  <script src="script.js"></script>
  <body>
  </html>

and the script is

  var el = document.getElementById("changeButton");
  el.onclick = function(){
    textChange("changetothis");
  }

  function textChange(text){
   document.title = text;
  }
Comments