Freddy Bausley
Freddy Bausley

Reputation: 35

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;

}

Upvotes: 0

Views: 1807

Answers (2)

Ahmed Anwar
Ahmed Anwar

Reputation: 51

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;
  }

Upvotes: 1

Steve
Steve

Reputation: 1

You can achieve your desired effect by using an anonymous function, like so:

document.getElementById("changeButton").onclick = function () {
  document.title = newTitle;
}

The variable 'newTitle' should be declared & initalized above this code somewhere in order for it to work.

Upvotes: 0

Related Questions