1

Rookie alert! Would you tell me why my Javascript code doesn't update the message. The browser runs HTML but ignores the Javascript code. What am I doing wrong?

<!DOCTYPE html>

<html>
<head>
  <title>Basic Function </title>

  <script type="text/javascript">


var msg = 'Sign up to receive our newsletter for 10% off!';

function updateMessage() {
  var el = document.getElementById('message');
  el.textContent = msg;
}

updateMessage();
  </script>
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>  
  </body>
</html>
VaVa
  • 410
  • 2
  • 14
  • 2
    your code will be executed too fast. `document.getElementById('message');` the Node with the id "message" not exists in the moment the code is executed. take a look at `window.onload` event. change `updateMessage()`=>`window.onload = updateMessage;` – Joshua K Sep 12 '15 at 14:39

6 Answers6

5

You're running the Javascript before you've loaded the body, the message element doesn't exist yet. Either move the script to the end of the <body>, or change the last line to:

window.onload = updateMessage;

so that the function will be loaded after the HTML is loaded.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

If the <script> tag is in the <head> element, it gets executed before the HTML elements in the <body> are created. You can put your script tag inside the <body> element, at the end of it, to solve the issue.

jrsala
  • 1,899
  • 12
  • 13
1

Assuming you don't simply have javascript disabled, you could add a window.onload=function(){ surrounding your code.

window.onload=function(){


    var msg = 'Sign up to receive our newsletter for 10% off!';

    function updateMessage() {
        var el = document.getElementById('message');
        el.textContent = msg;
    }

    updateMessage();

}

The reason for doing this is because your javascript code is inside your <head>. Thus, the javascript is loaded before the body. When the browser attempts to execute the javascript code, the message element isn't loaded yet and doesn't exist. By adding window.onload=function(){ to surround your code, your entire code will wait until the body is loaded before executing.

Zsw
  • 3,920
  • 4
  • 29
  • 43
1

When you call your javascript code, the 'message' element isn't already there. I would suggest one of the following two things:

+Put your javascript code at the end of the body ( note that it only need to be after 'message', but putting it at the end is generally the best option )

+Replace your call with window.onload = updateMessage, which will wait until all the page is loaded to execute your javascript

AdminXVII
  • 1,319
  • 11
  • 22
1

There are already lots of duplicate answers here but there is another way, especially if you want to keep your Javascript code in a script tag in the head. And that is, wrap your Javascript function call in setTimeout -- this causes the function to be executed after the DOM has been parsed, but before the entire window has been loaded.

It's a neat little trick that can be used when you don't have a framework's (such as jQuery) document/ready functionality. window.onload or putting the script at the bottom might cause significant delays if there is lots of heavyweight content (large images?) in the page.

<!DOCTYPE html>

<html>
<head>
  <title>Basic Function </title>

  <script type="text/javascript">
      var msg = 'Sign up to receive our newsletter for 10% off!';

      function updateMessage() {
        var el = document.getElementById('message');
        el.textContent = msg;
      }

      setTimeout(updateMessage);
  </script>
</head>

<body>
   <h1> Travel Worthy </h1>
   <div id="message">Welcome to our site!</div>
   <img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
</html>

Notice I have added a very large image to the page, but the updated message displays before the image fully loads.

If however instead of setTimeout(updateMessage); you use window.onload = updateMessage; as suggested in the currently accepted answer, your message will not get updated until the entire image loads (if you try this out, make sure you do a hard refresh after the first time so you are not getting it from your cache). Same goes for moving the script too far down the page (below the very large image for instance) as below. I honestly think, if you don't have a framework's document/ready functionality, using setTimeout in a script block in the head is the best solution.

MESSAGE NOT UPDATED UNTIL AFTER IMAGE LOADS:

<!DOCTYPE html>

<html>
<head>
  <title>Basic Function </title>
</head>

<body>
   <h1> Travel Worthy </h1>
   <div id="message">Welcome to our site!</div>
   <img src="http://cdn.spacetelescope.org/archives/images/publicationjpg/heic1502a.jpg" />
</body>
  <script type="text/javascript">
      var msg = 'Sign up to receive our newsletter for 10% off!';

      function updateMessage() {
        var el = document.getElementById('message');
        el.textContent = msg;
      }

      updateMessage();
  </script>
</html>
Dexygen
  • 12,287
  • 13
  • 80
  • 147
0

You are trying to make the changes before the DOM is loaded. See the code below,

<!DOCTYPE html>

<html>
<head>
  <title>Basic Function </title>     
</head>
<body>
<h1> Travel Worthy </h1>
<div id="message">Welcome to our site! </div>  
</body>
<script type="text/javascript">

var msg = 'Sign up to receive our newsletter for 10% off!';

function updateMessage() {
  var el = document.getElementById('message');
  el.textContent = msg;
}

updateMessage();
</script>
</html>
JGV
  • 5,037
  • 9
  • 50
  • 94
  • It's easier to debug if you can see what's going on. Next time open the developer tools in your browser and look for error messages in the console. I saw this: js.html:14 Uncaught TypeError: Cannot set property 'textContent' of null – duffymo Sep 12 '15 at 14:41
  • your code is not W3c conform. Don't post code with html validation errors. ty – Joshua K Sep 12 '15 at 14:42
  • I just used the code posted in question to give the suggestion. For some reason, I am not seeing "js.html:14 Uncaught TypeError: Cannot set property 'textContent' of null" message in the console. Can you provide more details? – JGV Sep 12 '15 at 14:48