Calculate Twitter message count and characters remaining using JavaScript
Hi, friends! I hope you are staying safe and well wherever you are. Out of all of the social media networks, I enjoy spending my time on Twitter. I like connecting with other developers and artists who share the same passions as I do.
Here’s a fun JavaScript tutorial I’ve created that you can try on your own. This tutorial will help beginners understand how the JavaScript HTML DOM (Document Object Model) works. Below is an example of a sample tweet:
We’ll start setting up the HTML document by adding our header, input field box, paragraph, button, and an area where the results will be displayed. You can use any icon you want above the header (mine is from Font Awesome):
What we’re doing is setting up the template that will allow a user to input the text, click on the Calculate button, and provide a result on the HTML page. When the button is clicked, it’ll trigger the myTwitterCount()
function to proceed with the calculation and manipulate the current HTML page to display the results. You’ll see how this works in a bit.
Let’s go ahead and add some customization to our CSS file. You’re more than welcome to use a different font and color scheme on your end.
Now the fun part - adding the JavaScript code to make the page interactive.
Here’s a breakdown of what’s happening with the JavaScript code:
- We’ll start by declaring the function
myTwitterCount
that will gather the value from our input, do the calculation on the length of characters, how many left are remaining, and post the results on the HTML page. - The variable
tweetMsg
will retrieve the value from our IDtweet
using thedocument
methodgetElementById()
. - The variable
tweetCharLeft
will determine the remaining characters left from the message by subtracting 280 from the number of total characters in the original message written using the length property, which is denoted astweetMsg.length
. - Once the calculations are done, we’ll go ahead and post the results on the HTML page using the
document
methodgetElementById()
with theinnerHTML
property. We’re retrieving the ID result from our HTML page. It’ll be a string message that’s concatenated to let the user know the results from what they’ve inputted in the text box.
You can check out the CodePen I’ve created if you want to play around with the script.
Hope this helps! If you happen to like this article, feel free to share and tweet me your thoughts.
Appalachian, Marketing, Equality
Love this! I'm tinkering with JS for the first time since the late-00's, and I'm going to challenge myself to make one of these too. Thanks for the inspiration!
Fullstack Engineer
Fun Project. Thanks for sharing :)
Comments (4)