Skip to content

Instantly share code, notes, and snippets.

@jkoudys
Created June 27, 2016 21:21
Show Gist options
  • Save jkoudys/05659a4fe5247529c70892cf6816f84d to your computer and use it in GitHub Desktop.
Save jkoudys/05659a4fe5247529c70892cf6816f84d to your computer and use it in GitHub Desktop.
document.addEventListener('DOMContentLoaded', function () {
// Grab a couple elements from the DOM
const button = document.querySelector('button');
const main = document.querySelector('main');
// Pull some data from an element
const originalColour = button.style.backgroundColor;
// Make a new Node, where we can put our results
const results = document.createElement('p');
main.appendChild(results);
// A countdown clock, that manipulates the DOM asynchronously
function startCountdown() {
let countdown = parseInt(button.dataset.countdown, 10);
setInterval(function () {
countdown--;
if (countdown > 0) {
results.textContent = `Counting down from ${countdown}!`;
} else {
results.textContent = 'Happy GNU Year!';
}
}, 1000);
}
// Make our button change colours on hover
button.addEventListener('mouseenter', function () {
button.style.backgroundColor = 'red';
});
button.addEventListener('mouseleave', function () {
button.style.backgroundColor = originalColour;
});
// Make our button start the countdown when clicked
button.addEventListener('click', startCountdown);
});
<!doctype html>
<html>
<head>
<title>Demo</title>
<style>
.hidden { display: none; }
</style>
<script src="./app.js"></script>
</head>
<body>
<header>
</header>
<main>
<button style="background-color: blue;" data-countdown="10">Click Me</button>
</main>
<footer>
</footer>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment