Game Development Reference
In-Depth Information
Whether the data attribute name could be better represented by a CSS class can be
argued in either direction. In this case, I chose to use a data attribute because then
the styling can be independent of anything, and that concern can be delegated to
another part of the application without any hesitation.
<button data-intent="play">Play Again</button>
<section id="mainContainer">
<div id="wordsToWrite"></div>
<div id="wordsWritten"></div>
<button data-intent="play">Play</button>
</section>
Here we have two separate buttons that share the same data attribute intent =
"play" . With that attribute present, and that value assigned, we can then some
JavaScript logic to handle those, and any other buttons, making their behavior pre-
dictable and universal.
// Select all buttons with a custom data
attribute of intent anda value of play
var playBtns =
document.querySelectorAll("button[data-intent='play']");
// Assign the same click handler to all of
these buttons
for (var i = 0, len = playBtns.length; i < len;
i++) {
playBtns[i].addEventListener("click",
doOnPlayClicked);
}
// Now every button with data-intent="play"
executes thisfunction when clicked
function doOnPlayClicked(event) {
event.preventDefault();
// Play button click behavior goes here
}
Search WWH ::




Custom Search