Search code examples
javascriptconfirm

Javascript confirm redirect does not work properly


i´m trying to have a confirm box before users click on an external link, Problem is my code redirect wether or not they click ok. It redirects on cancel also. What is wrong?

The Link calls it with onclick="confirmLeave();"

    function confirmLeave() {
    if (confirm("Weiterleitung\n\n text text")) {
    window.open('https://...')
    } 
    else {
    console.log('stay here.');
                        return false
                    }} 

Solution

  • I'm not sure what goes wrong in your code, but here you have a working snippet.

    function leavePage() {
      if (confirm("You sure ?")) {
        window.location.href = "http://www.google.com";
      } 
    }
    <button onclick="leavePage()">Click</button>