I need a javascript 'OK'/'Cancel' alert once I click on a link.
I have the alert code:
<script type="text/javascript">
<!--
var answer = confirm ("Please click on OK to continue.")
if (!answer)
window.location="http://www.continue.com"
// -->
</script>
But how do I make it so this only runs when clicking a certain link?
You can use the onclick
attribute, just return false
if you don't want continue;
<script type="text/javascript">
function confirm_alert(node) {
return confirm("Please click on OK to continue.");
}
</script>
<a href="http://www.google.com" onclick="return confirm_alert(this);">Click Me</a>
Single line works just fine:
<a href="http://example.com/"
onclick="return confirm('Please click on OK to continue.');">click me</a>
Adding another line with a different link on the same page works fine too:
<a href="http://stackoverflow.com/"
onclick="return confirm('Click on another OK to continue.');">another link</a>
just make it function,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
<a href="javascript:AlertIt();">click me</a>
In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML
HTML:
<a id="theLink">Click Me</a>
I could use the following jQuery to hookup an event to that specific link.
// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {
// The '#theLink' portion is a selector which matches a DOM element
// with the id 'theLink' and .click registers a call back for the
// element being clicked on
$('#theLink').click(function (event) {
// This stops the link from actually being followed which is the
// default action
event.preventDefault();
var answer confirm("Please click OK to continue");
if (!answer) {
window.location="http://www.continue.com"
}
});
});
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