webstuffshare.com

Don’t let your link that have a critical action (such as delete some data or something else) fly away on their own self, we must put a confirmation before do the action to prevent user’s mistake. Now, let us make that one.

Java Script has a built-in function to create a user confirmation box ( confirm() ), it means we can call that confirmation box to confirm user’s action. So if the user click a link, they must confirm that before we process the action. If the answer is cancel the default action will be cancelled and vice versa. We can use preventDefault() function to cancel the default action from our link. Take a look at following script. (Implementation #1).

$('.ask-plain').click(function(e) {
 
	e.preventDefault();
	thisHref	= $(this).attr('href');
 
	if(confirm('Are you sure')) {
		window.location = thisHref;
	}
 
});

If the user click the link we cancel its default action, grab its default link and confirm the user. If the user confirms his action then we’ll redirect to the default link. But that’s too plain, we’ll replace them with a cute one by adding some CSS properties and jQuery magic. (Implementation #2 and #3).

$('.ask').click(function(e) {
 
	e.preventDefault();
	thisHref	= $(this).attr('href');
 
	if($(this).next('div.question').length <= 0)
		$(this).after('<div class="question">Are you sure?<br/> <span class="yes">Yes</span><span class="cancel">Cancel</span></div>');
 
	$('.question').animate({opacity: 1}, 300);
 
	$('.yes').live('click', function(){
		window.location = thisHref;
	});
 
	$('.cancel').live('click', function(){
		$(this).parents('div.question').fadeOut(300, function() {
			$(this).remove();
		});
});

The process is similar to the first script, but we’ll use our customized confirmation box (div with class question) instead of confirm() function. By attaching div element after clicked link element, our confirmation box will appear and displaying a confirmation. If the user confirms his action then we’ll redirect to the default link, else we’ll remove our confirmation box. That’s it, we have a cute confirmation box ;)

Tags :   Code Snippet    CSS    Forms    jQuery  

Share :           [CodeSnippet] jQuery : Confirm User’s Action (via @hdytsgt)



webstuffshare RSS



  Similar Stuffs  

  3 Shouts to “[CodeSnippet] jQuery : Confirm User’s Action”  


  Shout Something  

  Follow Webstuffshare  
RSS
  FREE Subscribe  

Get Free Webstuffshare Daily Updates.

  Hot Stuffs  
  Recent Shouts