Search code examples
javascripthtmlconfirm

Clicking 'cancel' in confirm() method has the same result as clicking 'ok'


I am a beginner implementing a confirm method in my HTML code - when the user clicks on "x", they will be redirected to the home page. Otherwise, nothing happens.

My problem is that in confirm(), both "ok" and "cancel" options redirect to home page and I cannot figure out why.

I saw that many people have a similar problem, checked many forums and noticed that writing onclick="return confirmCancel() rather than onclick="confirmCancel()" helped in most of the cases but it did not solve the problem for me.

HTML:

<a onclick="return confirmCancel()"><img src="assets/cancel.svg"></a>

JS:

const confirmCancel = () => {
    confirm("All your progress will be lost. Are you sure you want to leave?");
    if (confirmCancel) {
        window.location.assign("index.html");
    } else {
        return false;
    }
}

Solution

  • You need to test the return value of confirm (rather than the truthiness of the confirmCancel function).

    const confirmCancel = () => {
        if (confirm("All your progress will be lost. Are you sure you want to leave?");) {
            window.location.assign("index.html");
        } else {
            return false;
        }
    }