Kati0208
Kati0208

Reputation: 63

Close current tab by a html button

I want to close the current tab of my program by a button which I created in HTML and gave him a click event so I want to close the tab in js by doing an onclick but when I click on my button nothing happens.

Here is my code:

<div class="modal-footer">
    <button class="btn btn-light" id="closebtn" onclick="closeBtnClicked"> Close </button>
    <button class="btn btn-primary">Save</button>
</div>

And this is my js function:

function closeBtnClicked(){
    window.close();
}

Upvotes: 0

Views: 4154

Answers (4)

sasodoma
sasodoma

Reputation: 56

There are two problems with your code. The first and more obvious one is that your onclick attribute value is missing the () after the function. Because of this, your function never actually got called.

However, when you fix this problem, you notice the other one: Calling the function window.close() in most modern browser will fail, if the window was not also opened by the same script (e.g. using the open() function).

According to Mozilla this is a security precaution, although I don't understand how a script closing its own tab could be exploited.

Upvotes: 1

thinke
thinke

Reputation: 311

You forgot "()", it's

onclick="closeBtnClicked()"

Upvotes: 0

Anon
Anon

Reputation: 528

The onclick attribute must contain a function call, not the function name. Simply change onclick="closeBtnClicked" to onclick="closeBtnClicked()".

See W3Schools for examples and a definition of the onclick attribute.

Upvotes: 2

Harshit
Harshit

Reputation: 895

Try this: by just calling close and onclick is a function so change that to closeBtnClicked().

function close_window() {
  if (confirm("Close Window?")) {
    close();
  }
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>

<body>

<a href="javascript:close_window();">close</a>

</body>
</html>

Upvotes: 0

Related Questions