jQuery special events
Custom click event: clickDisabled
http://benalman.com/news/2010/03/jquery-special-events/
HTML
<h1>
<a href="http://benalman.com/news/2010/03/jquery-special-events/" target="_top">jQuery special events</a>
» Custom click event: clickDisabled
</h1>
<p class="intro">(click box and links)</p>
<div id="test">
<div id="a">
a
<br/>
<a href="#foo" id="foo">foo</a>
<a href="#bar" id="bar">bar</a>
<a href="#baz" id="baz">baz</a>
</div>
</div>
<div id="nav">
<a href="#">cycle through sample $.clickDisabled selectors</a>
</div>
<div id="status"></div>
<div id="log"></div>
CSS
body { font-family: Arial, Helvetica, sans-serif; font-size: 0.8em; }
h1 { font-weight: 700; font-family: "Gill Sans", "Gill Sans MT", Arial, Helvetica, sans-serif; }
h1, a { color: #913D00; }
a:hover { color: #FF7F00; }
h1 { font-size: 120%; margin-bottom: 0.6em; }
.intro { font-style: italic; margin-top: 0.5em; }
#test, #nav, #status, #log {
margin-top: 1em;
}
#test div {
border: 1px solid #000;
margin: 1em 0;
padding: 0.5em 1em;
}
JavaScript
$(function(){
function log(){
$('#log').append([].join.call(arguments,', ')+'<br/>');
};
var i = 0,
state = 0,
states = [
{ selector: null, text: 'Nothing disabled.' },
{ selector: '#test a', text: 'Click disabled on A elements.' },
{ selector: '#test *', text: 'Click disabled on everything.' }
];
// Bind the click event to the links as well as parent div
// so we can see the event propagate.
$('#test *').click(function(){
log( ++i, '#' + this.id + ' clicked' );
});
// Cycle through sample $.clickDisabled selectors
$('#nav a').click(function(){
$.clickDisabled = states[ ++state % states.length ].selector;
return false;
});
// Keep the log output updated.
setInterval(function(){
$('#status').html( [ states[ state % states.length ].text,
'$.clickDisabled: ' + $.clickDisabled,
'Current URL: ' + location.href ].join('<br/>') );
},100);
});
//////////////////////////////////////////////////
// THE FOLLOWING CODE IS TAKEN FROM THE EXAMPLE //
//////////////////////////////////////////////////
(function($){
// A public property that can be changed at any time.
$.clickDisabled = null;
// Special event definition.
$.event.special.click = {
add: function( handleObj ) {
// Save a reference to the bound event handler.
var old_handler = handleObj.handler,
// The current element.
elem = $(this);
handleObj.handler = function( event ) {
if ( $.clickDisabled && elem.is( $.clickDisabled ) ) {
// If $.clickDisabled is specified and the element to which the
// callback is bound matches the specified selector, prevent the
// default action without stopping propagation, and don't call
// the originally bound event handler.
...