jQuery: check if a button is active or not

jQuery: check if a button is active or not

How to check if a given button has been clicked by users or not with jQuery.

On single-page apps it's very important to keep track of user's actions especially if the current page won't be reloaded often (this usually happens on AJAX-driven apps). Suppose that we have a series of buttons and we want to mark a button as inactive after a given period of time. This can be easily achieved with jQuery.

We say that a button is inactive only if it's not been clicked after n-seconds. To accomplish our task we basically need a timer that checks whether a button has been flagged as clicked. We can flag a button as clicked by using data attributes and also applying a special CSS class to it (in order to visually identify it as active).

Here's our implementation:


(function( $ ) {
	$.fn.disable = function( options ) {
		options = $.extend({
			interval: 3000,
			disabledClass: "disabled"
			
		}, options);
		
		return this.each(function() {
			var $element = $( this );
			
			$element.data( "disable", true );
			
			var timer = setInterval(function() {
				
				if( !$element.data( "activated" ) ) {
				  if( !$element.hasClass( options.disabledClass ) ) {
					   $element.addClass( options.disabledClass );
				  }
				}
				
			}, options.interval);
			
			$element.on( "click", function() {
				clearInterval( timer );
				if( $element.hasClass( options.disabledClass ) ) {
					$element.removeClass( options.disabledClass );
				}
				$element.data( "activated", true );
			});
			
		});
	};
	
	$(function() {
		$( ".btn" ).each(function() {
			var $btn = $( this );
			if( !$btn.data( "disable" ) ) {
				$btn.disable().on( "click", function( e ) {
					e.preventDefault();
				});
			}
		});
	});
	
})( jQuery );

You can see the demo below.

See the Pen jQuery: check if buttons are active by Gabriele Romanato (@gabrieleromanato) on CodePen.