butchering a BearBlog word counter for my own needs
So I’m not a good webdev or JS dev at ALL. Like, I can add and fix things but a large project I would have to spend a lot of time learning things. With that in mind, and after I finally switched to a paid BearBlog sub, I did some thinking about what I needed from the BearBlog editor. And basically all I need is a word counter. Simples.
Having 0 idea where to start, I did some digging and found almost exactly what I wanted: a ’time to read’ snippet from https://github.com/Froodooo/bear-plugins/blob/main/bear/reading-time.js. Ideally, this is intended to live on each post and give the reader some info of how long it’d take to read a post. But in the guts of this there is what I need: a way to get the word count, and a way to display it on the page.
I made a few changes to the original script and ended up with the following:
<script>
if (document.getElementsByName("body_content").length > 0) {
const wordCount = document.getElementsByName("body_content")[0].textContent.trim().split(/\s+/).length;
document
.querySelector("main")
.insertBefore(
document.body.appendChild(
Object.assign(
document.createElement("p"), {
className: "word-count",
innerHTML: `Word Count: ${wordCount}`
})),
document.querySelector("main").childNodes[parseInt(document.currentScript.getAttribute("data-before-child") ?? 4)]);
}
</script>This has some flaws though:
- It’s not particularly accurate. But that’s not important
- It’s static. This is the main drawback with it, is that it requires a page refresh to update. I did play around with
KeyboardEvents for quite a while and got something almost working, but decided that what I have is good enough - I have no idea if it’s good JS. Since I made only a few changes to the original, I’m relying on the possible fact that
Froodooowrites good JS. Well, if I get an angry email from Herman, I’ll know something’s up.
But so far it’s been great and quite informative. It’s also given me some new ideas of other scripts that I could do (spoiler: check the email button below).