Created
April 30, 2014 21:16
-
-
Save msrafi/11438748 to your computer and use it in GitHub Desktop.
BindIFEvent Handler - Bennadel
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
| // Wrap the plugin definition in a callback bubble so we can bind | |
| // it to the dollar sign. | |
| (function( $ ){ | |
| // This jQuery plugin creates proxied event handlers that | |
| // consult with an additional conditional callback to see if | |
| // the original event handler should be executed. | |
| $.fn.bindIf = function( | |
| eventType, | |
| eventHandler, | |
| ifCondition | |
| ){ | |
| // Create a new proxy function that wraps around the | |
| // given bind callback. | |
| var proxy = function( event ){ | |
| // Execute the IF condition callback first to see if | |
| // the event handler should be executed. | |
| if (ifCondition()){ | |
| // Pass the event onto the original event | |
| // handler. | |
| eventHandler.apply( this, arguments ); | |
| } | |
| }; | |
| // Bind the proxy method to the target. | |
| this.bind( eventType, proxy ); | |
| // Return this to keep jQuery method chaining. | |
| return( this ); | |
| }; | |
| })( jQuery ); | |
| // When the DOM is ready, intialize document. | |
| jQuery(function( $ ){ | |
| // Get a reference to the modal window. | |
| var modal = $( "#modal" ); | |
| // Bind the trigger link to show the modal window. | |
| $( "a" ) | |
| .attr( "href", "javascript:void( 0 )" ) | |
| .click( | |
| function( event ){ | |
| // Show modal window. | |
| modal.show(); | |
| // Prevent default. | |
| event.preventDefault(); | |
| } | |
| ) | |
| ; | |
| // Bind a mousedown event on the document so that we | |
| // can close the modal window when it is open. | |
| $( document ).bindIf( | |
| "mousedown", | |
| function(){ | |
| // Log to console for debugging. | |
| console.log( "Event handled." ); | |
| // Close the modal window. | |
| modal.hide(); | |
| }, | |
| function(){ | |
| return( modal.is( ":visible" ) ); | |
| } | |
| ); | |
| // Bind the mousedown event the modal window so we can | |
| // stop it from bubbling up to the document (ie. you | |
| // should be able to click IN the modal window without | |
| // it closing. | |
| modal.bind( | |
| "mousedown", | |
| function( event ){ | |
| event.stopPropagation(); | |
| } | |
| ); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment