Skip to content

Instantly share code, notes, and snippets.

@cagataycali
Last active November 25, 2021 02:48
Show Gist options
  • Save cagataycali/c5e6fe9c367fa14ddca8ba36849857a3 to your computer and use it in GitHub Desktop.
Save cagataycali/c5e6fe9c367fa14ddca8ba36849857a3 to your computer and use it in GitHub Desktop.
HTML Button generator
<html>
<head>
<title>Button Generator</title>
<style>
#container button {
padding: 1rem;
margin: 1rem;
border-color: transparent;
border-radius: 5px;
color: white;
width: 185px;
background-color: black;
font-weight: bold;
}
</style>
</head>
<body>
<div id="container">
<button data-count="0">Clicked 0 time</button>
</div>
<script>
const container = document.getElementById("container");
// Event delegation for further additions as button,
container.addEventListener("click", handleClick);
function handleClick(e) {
const { tagName } = e.target;
if (tagName === "BUTTON") {
return handleButtonClick(e);
}
}
function handleButtonClick(e) {
// Stop propagation
e.stopPropagation();
let count = e.target.dataset.count;
count++;
e.target.setAttribute("data-count", count);
e.target.innerText = `Clicked ${count} times`;
createCounterButton(container, 0);
return false;
}
function createCounterButton(container, count = 0) {
const button = document.createElement("button");
button.setAttribute("data-count", count);
button.innerText = "Clicked 0 time";
container.appendChild(button);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment