1

Need the following code to work and make a confirmation alert appear after clicking on a button.

It's kinda of a "exit website button".

Confirmation appears: Clicks "OK" > current window close; Clicks "Cancel" > confirmation alert close;

HTML

<a href="#"><i class="fa fa-power-off" onclick="closeWebsite()"></i></a></div>

Javascript

<script>
  function closeWebsite(){
    window.close();
  }
</script>

Where's my mistake? I'm currently learning Javascript.

M Hamza Javed
  • 1,269
  • 4
  • 17
  • 31
Lucaz Nunes
  • 35
  • 1
  • 8
  • 1
    "Where's my mistake?" — What makes you think you've made a mistake? Why do you expect that code to display a confirmation alert? What does that code actually do? – Quentin Feb 08 '17 at 09:33

4 Answers4

1

You can only use JavaScript to close a window/tab that was spawned via JavaScript.

Just create file with name index.html and open the another tab, just first click on Open and Then on Close you will get the answer

<a href="index.html" target="blank">Open</a>
<a href="#" onclick="closethis();return false;">close</a>

<script>
function closethis()
{
    if(confirm("Close Window?")){
        close();
    }
}
</script>
Kirankumar Dafda
  • 2,354
  • 5
  • 29
  • 56
0

Does this help you?

function closeWebsite(){
 var resultConfirm = confirm("Confirm window close?");
 if (resultConfirm == true) {
  console.log("closing window...");
  window.close();
 }
}
<a href="#"><i class="fa fa-power-off" onclick="closeWebsite()">Close window</i></a></div>
Ala Eddine JEBALI
  • 7,033
  • 6
  • 46
  • 65
0

You cannot close a window with javascript that you did not open. It will not work in chrome or firefox.

See https://stackoverflow.com/a/19768082/2623781 for more information.

Community
  • 1
  • 1
Gautam Patadiya
  • 1,401
  • 14
  • 19
0

I think what you are really looking for is the window.beforeunload event, which get triggered when you leave the website.

It does not matter how you leave it (by closing the tab/browser or surfing to another website).

Here you find an example of how it works: window.onunload is not working properly in Chrome browser. Can any one help me?

Community
  • 1
  • 1
Armin
  • 15,582
  • 10
  • 47
  • 64