Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept click event on a button, ask for confirmation, then proceed

Tags:

Based on a variable SomeCondition, I need to intercept a click event on a button, and ask for confirmation, if they say ok, proceed, otherwise ignore click.

So something like:

if(SomeCondition) {  // disable click on button  var isOk = window.confirm("Are you sure?");  if(isOk) {         $("#button1").click(); }  } 

Note: button1 has already been wired up with a click event via javascript from an external .js file that I can't change.

I don't know what the click event was bound too, so I have to disable the click if SomeCondition is true, then ask for confirmation, then continue with the click.

like image 796
Blankman Avatar asked Jan 12 '11 22:01

Blankman


People also ask

Which event execute when the button is clicked?

The onclick event occurs when the user clicks on an element.

What is click () method?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.

How can I capture the right click event in JavaScript?

To capture the right-click event in JavaScript, we can listen for the contextmenu event. el. addEventListener( "contextmenu", (ev) => { ev. preventDefault(); //... }, false );

What is a button click event?

The Click event is raised when the Button control is clicked. This event is commonly used when no command name is associated with the Button control (for instance, with a Submit button). For more information about handling events, see Handling and Raising Events.


1 Answers

Process isOK your window.confirm within the function of the button

$('#button1').click(function(){     if(window.confirm("Are you sure?"))      alert('Your action here'); }); 

The issue you're going to have is the click has already happened when you trigger your "Are You Sure" Calling preventDefault doesn't stop the execution of the original click if it's the one that launched your original window.confirm.

Bit of a chicken/egg problem.

Edit: after reading your edited question:

    var myClick = null;      //get a list of jQuery handlers bound to the click event     var jQueryHandlers = $('#button1').data('events').click;      //grab the first jquery function bound to this event     $.each(jQueryHandlers,function(i,f) {        myClick = f.handler;         return false;      });      //unbind the original     $('#button1').unbind('click');      //bind the modified one     $('#button1').click(function(){         if(window.confirm("Are You Sure?")){             myClick();         } else {             return false;         }     }); 
like image 73
Jason Benson Avatar answered Oct 06 '22 19:10

Jason Benson