I want this link to have a JavaScript dialog that asks the user “Are you sure? Y/N”.
<a href="delete.php?id=22">Link</a>
If the user clicks “Yes”, the link should load, if “No” nothing will happen.
I know how to do that in forms, using onclick running a function that returns true or false. But how do I do this with an <a> link?
Inline event handler
In the most simple way, you can use the
confirm()function in an inlineonclickhandler.Advanced event handling
But normally you would like to separate your HTML and Javascript, so I suggest you don’t use inline event handlers, but put a class on your link and add an event listener to it.
This example will only work in modern browsers (for older IEs you can use
attachEvent(),returnValueand provide an implementation forgetElementsByClassName()or use a library like jQuery that will help with cross-browser issues). You can read more about this advanced event handling method on MDN.jQuery
I’d like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences. Just for fun, here is how this would look with jQuery: