Tue 26 Jun 2007

This is a little tip that I discovered a while ago but which I’m always forgetting, so I thought I’d post it here where I woudn’t lose it! Sometimes you’ll have a link on a web page which actually does something to a database, deletes the current thing for example. In those circumstances you want to have some sort of “Are you sure?” confirmation.

Javascript has a confirm dialog that you can use, but because you can use the return value of a method to determine event bubbling, you can use this really neatly to give optional links as follows:

<a href="http://www.isocra.com" onclick="javascript:return confirm('Are you sure you want to go to our home page ?')">
Click here to go to home page</a>

And of course you can try it yourself: Click here to go to home page.

If you click OK, then the confirm returns true and the link is followed. If you click Cancel, then confirm returns false and the event isn’t bubbled up to the href handler and so the link isn’t followed and you stay on the same page.



x
This website uses cookies. More info. That's OK