Click Count with JavaScript


Button was clicked - 0 - times.


     Above click event can easily be triggered by little script. We can use that for our blog or in web game to collect click. Below is the script_


     Here we used getElementById() to get certain elements and set an onClick() attribute and incremented the count number. This the most easiest way to get this task done. However, there are so many other ways too.
     Another approach will be storing count data locally. We can tore data inside of the browsers to make the process fast. I like to use localStorage in this case. Take a look at the script below_  


     I prefer to use localStorage. Most of the major browsers support it. At some point, before HTML5, only options was using cookies to store data. Performance was not as smooth as local storage. Even storage limit wasn't that big, where local storage can store up to 5MB as per today. Local storage is more secure and doesn't have any impact on browser's performances. Just to keep in mind, localStorage is kind of object that stores data without any expiration date. So, data will not be deleted when the browser is closed, and will be available the next day, week, or year. On the other hand, sessionStorage can also store data and will be vanished once the browser tab is closed. 

     For adding more fun, play with these buttons below_


We are counting how many times the first button is hovered. Hovering over RESET button will set the count to it's initial state. 


Yep, we set onmouseover attribute to the button to popup an alert.

No comments:

Post a Comment