0

I figured this out a while ago, but all of my files have been deleted and the only backup I have was from a couple weeks ago... anyways, I've followed the book and a few websites on event handling, but I don't know how to remove the inline Javascript. This is what I've already looked at:

addEventListener vs onclick

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_close

button.html File:

<html>
<head>
    <script src="window.js"></script>
</head>
<body>
    <button type="button" id="Start Process">Start Process</button>
</body>
</html>

window.js File:

function myFunction() {
    window.open("http://www.w3schools.com");
}

var Process = document.getElementById('Start Process');
Process.onclick = myFunction;
Community
  • 1
  • 1
user3334776
  • 113
  • 1
  • 10
  • 2
    Move your script to the bottom of the page. The button doesn't exist at the time the script loads. Either that or wrap things in a `window.onload` function. – Jeremy J Starcher May 03 '14 at 20:06

1 Answers1

0

The code seems to work fine. Make sure that you import the <script> at the end of the page. Otherwise, the button wouldn't exist at the time when the script loads.

<html>
<head>
     <!-- Remove the script from here -->
</head>
<body>
    <button type="button" id="Start Process">Start Process</button>

    <!-- Place the script here -->
    <script src="window.js"></script>
</body>
</html>

If it still doesn't work, try removing the space from the id.

In the HTML:

<button type="button" id="StartProcess">Start Process</button>

In JS:

var Process = document.getElementById('StartProcess');

The id attribute shouldn't contain a space. According to HTML 4.0 specification for basic types:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

And according to HTML5 specification:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

John Bupit
  • 10,406
  • 8
  • 39
  • 75
  • While that's true for HTML4, I don't think it is for HTML5. Either way, I'm pretty sure `getElementById()` in most browsers will still find IDs that contain a space. http://jsfiddle.net/4hX24/ – cookie monster May 03 '14 at 20:14
  • Well, I guess you are correct. [The code provided by OP](http://jsfiddle.net/d5SFt/) works fine. The problem is probably the placement of the ` – John Bupit May 03 '14 at 20:20
  • 1
    I just checked the [HTML5 spec](http://www.w3.org/TR/html5/dom.html#the-id-attribute), and they do say that space characters are not allowed, however pretty much any other character does seem to be permitted. While some browsers do fetch by IDs with spaces, I'm not sure if all do. – cookie monster May 03 '14 at 20:22
  • @user3334776 Are you placing the script at the end bottom of the page? – John Bupit May 03 '14 at 20:26