Event Handlers
Putting your CSS and JS in separate files.
Starting with this example:
<div id="container"></div>
<script>
const container = document.getElementById("container");
const kittenImg = document.createElement("img");
kittenImg.src = "http://placekitten.com/g/200/300";
container.appendChild(kittenImg);
</script>
Move the JS to a separate file called script.js
:
<script src="script.js"></script>
What happens if...?
Put the
<script>
tag before the<div>
Put it after the
div
Put it in the
<head>
Keep it in the
<head>
and adddefer
to the tag - this is what we want to do going forward.
Show that we can also add stylesheets by linking them with the <link>
tag (demo with a background color or something).
<head>
<link rel="stylesheet" href="styles.css" />
</head>
Textboxes!
Extend the kitten example to use a textbox to do input.
Introducing input boxes with
<input type="text">
Using
.value
to get the value of the text box in JavaScript
index.html
<input id="mytextbox" type="text" />
<button onclick="handleClick()">Add</button>
<div id="container"></div>
script.js
function addKitten() {
const container = document.getElementById("container");
const kittenImg = document.createElement("img");
kittenImg.src = "http://placekitten.com/g/200/300";
container.appendChild(kittenImg);
}
function addPuppy() {
const container = document.getElementById("container");
const puppyImg = document.createElement("img");
puppyImg.src = "https://place-puppy.com/300x300";
container.appendChild(puppyImg);
}
function handleClick() {
const textBoxContents = document.getElementById("mytextbox").value;
if (textBoxContents === "kitten") {
addKitten();
} else if (textBoxContents === "puppy") {
addPuppy();
}
}
References
Last updated
Was this helpful?