Created
December 4, 2013 20:32
-
-
Save lkacenja/7795006 to your computer and use it in GitHub Desktop.
A simple script to prevent users from clicking a button or link many thousand times.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
/** | |
* Jquery function to attach/detach click stopping. | |
* Call on link or input: $('selector').clickStopper({message: 'Optional message'}); | |
* Destroy by calling again. | |
*/ | |
$.fn.clickStopper = function(options) { | |
// return this to maintain chainability | |
return this.each(function() { | |
if ($(this).hasClass('click-stopper-processed')) { | |
detach($(this)); | |
} | |
else { | |
attach($(this), options); | |
} | |
}); | |
} | |
/** | |
* Private variables and methods | |
*/ | |
var defaultMessage = 'Loading...'; | |
/** | |
* Attach our behavior to an element. | |
*/ | |
function attach($el, options) { | |
$el.addClass('click-stopper-processed'); | |
options = options || {}; | |
if ($el.is('a')) { | |
options.originalValue = $el.text(); | |
} | |
else { | |
options.originalValue = $el.val(); | |
} | |
$el.data('click-stopper-options', options); | |
$el.click(handleClick); | |
} | |
/** | |
* Detach our behavior from an element. | |
*/ | |
function detach($el) { | |
$el.unbind('click'); | |
$el.removeClass('click-stopper-processed').removeClass('clicked'); | |
var options = $el.data('click-stopper-options'); | |
$el.data('click-stopper-options', {}); | |
if ($el.is('a')) { | |
$el.text(options.originalValue); | |
} | |
if ($el.is('input')) { | |
$el.val(options.originalValue); | |
$el.parents('form').unbind('submit'); | |
} | |
} | |
/** | |
* Click handler | |
*/ | |
function handleClick() { | |
if (!$(this).hasClass('clicked')) { | |
var options = $(this).data('click-stopper-options'); | |
if ($(this).is('a')) { | |
$(this).text(options.message || defaultMessage); | |
} | |
else { | |
$(this).val(options.message || defaultMessage); | |
} | |
$(this).css({opacity: .75}); | |
$(this).addClass('clicked'); | |
} | |
else { | |
if ($(this).is('input')) { | |
$(this).parents('form').submit(function() { | |
return false; | |
}); | |
} | |
if ($(this).is('a')) { | |
return false; | |
} | |
} | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment