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.
The onclick event occurs when the user clicks on an element.
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.
To capture the right-click event in JavaScript, we can listen for the contextmenu event. el. addEventListener( "contextmenu", (ev) => { ev. preventDefault(); //... }, false );
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.
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; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With