I’m working on a simple Javascript(JS) application involving event listeners. This app involves taking input from a user in form of a click event. Each click should register a click count within 30 seconds. At the end of the 30 seconds it should provide a sum of the clicks and a message providing the click count multiplied by 2.
I was stuck on one part of this involving multiple event listeners on one element as I wanted an element on the page to begin the timer as well as begin the click count as soon as the user clicked on the element. I was originally trying to do this with JS by adding an event listener to to the element with the respective function. I learn’t quickly that this wasn’t working. In JS you cannot have multiple listeners passed in to a single event listener unless you use Event Bubbling. I tried this but it didn’t work with the logic for my app so I ended up using jQuery instead.
With a bit of research on jQuery I did find some answers on Stack Overflow referencing the .bind() method however according to the official documents this method has been deprecated and the .on() method has now superseded it so I ended up using this method.
The next hurdle was turning off the click event for the timer function after the first click but to continue the click event for the click count until the timer reached 30 seconds. In this scenario I couldn’t get the jQuery working for both click events, after a bit of fiddling around on JSfiddle I could get it working in this order by using a combination of jQuery and JS - the jQuery handled the turning on/off of the timer event and the JS handled the click count and other functions.
The last hurdle I’m currently working through is a function to reset the timer and the click count by clicking on a reset button. The issue is that clicking the reset button clears the timer and the JS resets the HTML, however the event listener for the count does not reset. So while I work on this issue and to get the app running I have currently installed a stop-gap measure which reloads the page resetting the app. More on this once I figure out the code.
Some resources that I found useful for trouble shooting:
- https://gomakethings.com/listening-to-multiple-events-in-vanilla-js/
- https://gomakethings.com/attaching-multiple-elements-to-a-single-event-listener-in-vanilla-js/
- http://api.jquery.com/bind/#entry-longdesc
- https://api.jquery.com/click/