jQuery special events
Custom clickoutside event
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 clickoutside event
</h1>
<p class="intro">(click boxes, non-boxes, whatever)</p>
<div id="test">
<div id="a">
a
<div id="b">
b
<div id="c">c</div>
<div id="d">d</div>
</div>
<div id="e">
e
<div id="f">f</div>
<div id="g">g</div>
</div>
</div>
</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 div {
border: 1px solid #000;
margin: 1em 0;
padding: 0.5em 1em;
}
#a, #b, #e {
padding-bottom: 0 !important;
}
#log {
margin-top: 1em;
}
JavaScript
$(function(){
$('#d').on('custom', {otherParam:'uha-ha!'}, function(event, param1, param2){
alert(param1 + "\n" + param2); // так осуществляется доступ к данным extraParameters
alert(event.data.otherParam); // а так к данным eventData
});
// вызовим событие методом trigger, в результате будет запущен наш обработчик
$('#d').trigger('custom', ['Custom', 'Event']);
function log(){
$('#log').append([].join.call(arguments,', ')+'<br/>');
};
// Clear the log on click.
$(document).bind( 'click', function(){ $('#log').empty(); });
// This should fire first.
$('#test div').bind( 'clickoutside', function(event){
var clicked = event.target;
log( '1. clickoutside: #' + this.id,
'(clicked: ' + (clicked.id ? '#' + clicked.id : clicked.tagName) + ')' );
//event.stopImmediatePropagation(); // Un-comment to stop immediate propagation.
});
// This should fire second.
$('#test div').bind( 'clickoutside', function(event){
log( '2. clickoutside' );
});
//$('#test div').unbind( 'clickoutside' ); // Un-comment this line to un-bind event handlers.
});
//////////////////////////////////////////////////
// THE FOLLOWING CODE IS TAKEN FROM THE EXAMPLE //
//////////////////////////////////////////////////
(function($){
// A collection of elements to which the clickoutside event is bound.
var elems = $([]);
// Special event definition.
$.event.special.clickoutside = {
setup: function(){
// Add this element to the internal collection.
elems = elems.add( this );
// If this is the first element to which the event has been bound,
// bind a handler to document to catch all 'click' events.
if ( elems.length === 1 ) {
$(document).bind( 'click', handle_event );
}
},
teardown: function(){
// Remove this element from the internal collection.
elems = elems.not(...