Skip to content

Instantly share code, notes, and snippets.

@martajohnsson
Forked from Jimmydalecleveland/index.html
Created December 7, 2021 20:53
Show Gist options
  • Save martajohnsson/87bffce2dec7656244df2c3e9f5214df to your computer and use it in GitHub Desktop.
Save martajohnsson/87bffce2dec7656244df2c3e9f5214df to your computer and use it in GitHub Desktop.
Minimal example of state and class instantiation/presentation from JS to HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Html JS class example</title>
</head>
<body>
<h1>HTML JS Class Example</h1>
<input id="dogNameInput" type="text" value="milo" />
<button id="createDog" type="button">
Adopt Dog (create Dog instance)
</button>
<br />
<h2>Current Dog</h2>
<h3>Name: <span id="dogName"></span></h3>
<button id="dogBarkButton" type="button">Ask dog to bark</button>
<p id="dogBark"></p>
<script src="index.js"></script>
</body>
</html>
// Grab all html elements that will be needed ahead of time.
const createDogButton = document.getElementById("createDog");
const dogNameInput = document.getElementById("dogNameInput");
const dogName = document.getElementById("dogName");
const dogBarkButton = document.getElementById("dogBarkButton");
const dogBark = document.getElementById("dogBark");
// This is our rudimentary "state", so the current dog can
// be stored here and accessed throughout the life of the app.
let dogInstance;
// Add event listener to chosen button element which calls our
// function (2nd arg) when clicked.
// This function creates a `Dog` instance, then stores it in
// our global state (top level `dogInstance` variable).
// It also takes the name and sets it as text in the html.
createDogButton.addEventListener("click", function (_) {
// store the current dog instance
dogInstance = new Dog(dogNameInput.value);
console.log(dogInstance);
// display name in html
dogName.innerText = dogInstance.name;
// optional: clear "dogBark" sentence when new dog is adopted
dogBark.innerText = "";
});
// Display dog bark sentence to chosen html element when chosen button clicked.
dogBarkButton.addEventListener("click", function (_) {
dogBark.innerText = dogInstance.bark();
});
// This class could be exported from another file if desired
class Dog {
constructor(name) {
this.name = name;
}
bark() {
return `${this.name} says "woof".`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment