Skip to content

Commit

Permalink
feat: fire a DOM event when a clap occurs, with the new clap count
Browse files Browse the repository at this point in the history
  • Loading branch information
ColinEberhardt committed Feb 26, 2019
1 parent b8350d2 commit cde3ba9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
8 changes: 7 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,18 @@
</style>
</head>
<body>
<applause-button id="applause" multiclap="true" url="applause-button.com/"/>
<applause-button id="applause" multiclap="true" url="google.com"/>
<script type="text/javascript">

const button = document.getElementById("applause");

button.initialClapCount.then(function(count) {
console.log("initial clap count", count);
});

button.addEventListener("clapped", function(event) {
console.log("button clapped", event.detail);
});
</script>
</body>
</html>
24 changes: 20 additions & 4 deletions src/applause-button.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ class ApplauseButton extends HTMLCustomElement {
this._totalClaps = 0;

let initialClapCountResolve;
this._initialClapCount = new Promise(resolve => (initialClapCountResolve = resolve));
this._initialClapCount = new Promise(
resolve => (initialClapCountResolve = resolve)
);

// buffer claps within a 2 second window
this._bufferedClaps = 0;
Expand All @@ -126,17 +128,31 @@ class ApplauseButton extends HTMLCustomElement {
return;
}

// fire a DOM event with the updated count
const clapCount =
Number(this._countElement.innerHTML.replace(",", "")) + 1;
this.dispatchEvent(
new CustomEvent("clapped", {
bubbles: true,
detail: {
clapCount
}
})
);

// trigger the animation
toggleClass(this, "clap");

// buffer the increased count and defer the update
this._bufferedClaps++;
this._updateClaps();

// increment the clap count after a small pause (to allow the animation to run)
setTimeout(() => {
this._countElement.innerHTML = formatClaps(
Number(this._countElement.innerHTML.replace(",", "")) + 1
);
this._countElement.innerHTML = formatClaps(clapCount);
}, 250);

// check whether we've exceeded the max claps
if (this.multiclap) {
if (this._bufferedClaps + this._totalClaps >= MAX_MULTI_CLAP) {
this.classList.add("clap-limit-exceeded");
Expand Down

0 comments on commit cde3ba9

Please sign in to comment.