Skip to content

Instantly share code, notes, and snippets.

@elijahmanor
Created February 25, 2012 05:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elijahmanor/1906622 to your computer and use it in GitHub Desktop.
Save elijahmanor/1906622 to your computer and use it in GitHub Desktop.
Find the jQuery Bug #5: Solution
(function( $ ) {
$.fn.confirmAction = function() {
return this.each( function() {
var $this = $( this ),
confirmText = $this.data( "confirmText" );
$this.bind( "click.confirmAction", function( e ) {
if ( confirmText ) {
if ( confirm( confirmText ) ) {
console.log( "Confirmed" );
} else {
console.log( "Denied" );
e.preventDefault();
e.stopImmediatePropagation();
}
}
});
});
};
})( jQuery );
// ... more code ...
$( "button" ).confirmAction();
$( "button:first" )
.unbind( ".confirmAction" )
.data( "confirmText", // <-- Use the .data() method!
"Are you really really sure you want to submit?" )
.confirmAction();
// ... more code ...
<button
data-confirm-text="Are you really sure you want to submit?"
data-math="true"
data-operators='[ "+", "-", "*" ]'
data-retries="3"
data-options='{ "debug": true }'>
Submit with Confirmation</button>​
var button = $( "button" );
console.log( button.data( "confirmText" ) ===
"Are you really sure you want to submit?" ); // true
console.log( button.data( "math" ) === true ); // true
console.log( button.data( "operators" ).length === 3 ); // true
console.log( button.data( "retries" ) === 3 ); // true
console.log( button.data( "options" ).debug === true );​ // true
<!-- Intercept click event and confirm before proceeding -->
<button
data-confirm-text="Are you really sure you want to submit?">
Submit with Confirmation</button>
(function( $ ) {
$.fn.confirmAction = function() {
return this.each( function() {
var $this = $( this ),
confirmText = $this.data( "confirm-text" );
$this.bind( "click.confirmAction", function( e ) {
if ( confirmText ) {
if ( confirm( confirmText ) ) {
console.log( "Confirmed" );
} else {
console.log( "Denied" );
e.preventDefault();
e.stopImmediatePropagation();
}
}
});
});
};
})( jQuery );
// Delegate click event on buttons to the document (similar to .live)
$( document ).on( "click", "button", function() {
alert( "Submit Form: Live" );
});
// Run plugin against all the buttons on the page
$( "button" ).confirmAction();
// Undo the plugin for the 1st button, modify data, & reinitialize
$( "button:first" ) // Grab 1st button on the page
.unbind( ".confirmAction" ) // Remove all namespaced event handlers
.attr( "data-confirm-text", // Update changes to HTML5 data-attr
"Are you really really sure you want to submit?" )
.confirmAction(); // Reinitialize plugin
// Bind click event on the buttons (similar to .bind)
$( "button" ).on( "click", function() {
alert( "Submit Form: Bind" );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment