This is generally done to ensure that web spiders and bots that access your page, do not arbitrarily invoke the target components on the page. Another example may be that you want to present certain content to your user, an advert, or a video presentation prior to enable additional content. In this tutorial, we are going to cover how to build a countdown timer that can be used to delay a button from being enabled on the page. This can be an effective way to ensure that your visitor is a human and also require that a delay occurs prior to serving the visitor the additional content. This additional content could be a video, a download link, or some other resource on your website.
The HTML
We will start with a simple HTML example. All we need for this example is a simple
The CSS
We use CSS to style our timer as well as the other components used in this demo such as the div elements that surround the timer and button. In our CSS sample, we use a different class for the enabled and disabled button.
JavaScript and jQuery
Most of the code used in this example is pure JavaScript. However, there are a few lines of jQuery included. So make sure that you reference the jQuery library in your page. In this example, you should notice that most of the code is written in pure JavaScript. However, there are three lines of code that leverage the jQuery library. The first two jQuery statements deal with the removal of the disabled attribute and class, and the enabling of the btnEnable class on the HTML button. The third creates an animated effect and fades the timer over 2500 milliseconds. It is not required to use jQuery for this example, but I did include it only because jQuery makes those particular steps much easier when compared with the JavaScript equivalent. In this example, we assigned the sec variable to 15 which is the number of seconds we want our timer to start the countdown at. Once the countdown reaches ’00’, the button is enabled. We used the setTimeout method to create a delay of 1000 milliseconds or 1 second before the countDown() function is executed again. Once the sec variable is equal to ‘0’, the function exists and is no longer executed.