Click on a buttom and a prompt will appear

3

I have a button , and I want you to click a prompt to ask if you really want to leave the page, with 2 options: Confirm or cancel.

If you click confirm, it goes to the button link, otherwise the prompt closes and nothing happens.

How can I do this?

    
asked by anonymous 24.08.2017 / 13:58

3 answers

6

You can do with a same link tag ( <a></a> ) and the confirm function of JavaScript. Example:

<a href="https://www.google.com/" target="_blank" onclick="return confirm('Deseja realmente sair?');">Sair do site</a>

Detailing:

The onclick event is added to the a tag that returns the result of the confirm function.

The confirm function is native to JavaScript, and opens a window displaying the text passed as a parameter, an 'OK' button, and a 'Cancel' button. If the user clicks OK, the function returns true . If the user clicks Cancel, the function returns false .

When you return false to the onclick event, it stops executing the default action of the element, which in the case of the a tag is the call to the link indicated in the href attribute.

  

Note: Semantically, the most appropriate for this action would be the use of the <a></a> tag, since by definition it indicates the link of the current page with another page. You can read more about setting and using the a tag at: link

    
24.08.2017 / 14:11
3

You can do this by placing the link of the page that should be directed already in JavaScript:

btn = document.getElementById('btn');

btn.addEventListener('click', function() {
  var b = confirm('Tem certeza que quer sair?');
  if (b){
    window.location = "http://pt.stackoverflow.com";
  }
});
<button id="btn">Sair</button>
    
24.08.2017 / 14:13
1

Workaround using button :

function confirmaSaida() {
  var confirmado = confirm("Deseja realmente sair da página?");

  if (confirmado === true) {
      self.location = "https://www.google.com";
  }
}
<input type="button" value="Sair da página" onclick="confirmaSaida();" />

Placing the link in tag input :

function confirmaSaida() {
  var confirmado = confirm("Deseja realmente sair da página?");

  if (confirmado === true) {
      self.location = document.getElementById("btn").getAttribute("data-link");
  }
}
<input id="btn" name="btn" type="button" value="Sair da página" onclick="confirmaSaida();" data-link="https://www.google.com" />
    
24.08.2017 / 14:17