0

It keeps saying my variable is null even though it is assigned to a button in HTML. It doesn't allow the button press to work. The variable is "clickMe"

var yourName;   //global variable accessible to all functions

function showAnotherMessage() {
    alert("Hi " + yourName + ".\nThis is an alert message is no longer defined\nin the HTML but in a JavaScript file");
}

function init() {
    yourName = prompt("Hi. Enter your name.\nWhen the browser window is first loaded\nthe function containing this prompt window is called.", "Your name");
    var clickMe = document.getElementById("buttonclick");
  clickMe.onclick = showAnotherMessage;
    }

window.onload = init();
4
  • var clickMe = document.getElementById("buttonclick"); ... do you have a html element with id="buttonclick" - exactly "buttonclick", not "buttonClick" or "buttonclick " Commented Apr 5, 2017 at 23:57
  • yes, the id is assigned to a button. <p><button type="button" id="buttonclick">Click Me!</button></p> Commented Apr 5, 2017 at 23:58
  • 4
    window.onload = init(); should be window.onload = init; Commented Apr 5, 2017 at 23:59
  • 1
    wow, thankyou so much lol Commented Apr 6, 2017 at 0:02

1 Answer 1

2

Avoid window.onload because it's fired too late in the page lifecycle - it's only fired after everything is loaded, including all images - which can be up to several seconds after the page has loaded.

Instead, use the DOM events API, and use the DOMContentLoaded event:

window.addEventListener('DOMContentLoaded', function(e) {

    // page startup code goes here
} );

Another reason to avoid window.onload = ... is that it will overwrite any previous event-handler for the onload event, whereas addEventListener does not remove any previous event handler.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.