Reputation: 109
I am trying to figure out how to get javascript to work with html in a separate file so that I can follow this tutorial https://www.w3schools.com/howto/howto_css_modals.asp and I'm having trouble getting my alert to pop up.
Here is my code.
So far I've only been able to get a button that doesn't do anything.
var hellobutton = document.getElementById("hello");
hellobutton.onclick = function() {
alert("Hello World")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/static/main.css">
<script type="text/javascript" src="/static/main.js"></script>
<title>Title</title>
</head>
<body>
<div class="content-section">
<h1>Page</h1>
<input type = "button" id="hello" value = "Say Hello" />
</div>
</body>
</html>
The code works here but not on my computer.
Upvotes: 1
Views: 93
Reputation: 811
It throws an error at line 2 because it couldn't find any element with that criteria already loaded and so it returns null at line 1. The value null is "nothing" so you can't set the onclick event of "nothing". One way to fix this is to load the js after the html element is loaded(no need to edit the js file):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/static/main.css">
<title>Title</title>
</head>
<body>
<div class="content-section">
<h1>Page</h1>
<input type = "button" id="hello" value = "Say Hello" />
</div>
<script type="text/javascript" src="/static/main.js"></script>
</body>
</html>
Or also by calling the js code only when the document is loaded(no need to edit html file):
document.addEventListener('DOMContentLoaded', function() {
var hellobutton = document.getElementById("hello");
hellobutton.onclick = function() {
alert("Hello World")
}
}, false);
I found this code here.
Upvotes: 1