The confirm() method

The confirm() method gives the viewer a chance to confirm or cancel an action. It returns a Boolean value of true or false and its result is usually assigned to a variable.

var ItIsSure = window.confirm("Are you sure?");

Let’s say that you have a link to another page on your page and you want the viewer to confirm before leaving the page.

<body>

<a href="http://javascript.saigon.ro" id="JS_link">Go to dan.Saigon.RO</a>

<script type="text/javascript" >
var theLink = document.getElementById("JS_link");
theLink.onclick = function () {
	var ItIsSure = window.confirm("Are you sure you want to follow the link?");
	if (!ItIsSure) {
		window.alert("OK, stay here! You are safe with me!");
		return false;
		}
}
</script>

</body>

If the viewer clicks OK then the function returns true and the viewer is taken to the link. If Cancel is clicked the function returns false, the link won’t be followed, and an alert is sent to the viewer.

Leave a Reply