Suds
Suds

Reputation: 37

Window focus is not working in Javascript

When I click on the Notebook button I want it to open notebook.html, if I click it a second time I want Notebook.html to come in to focus WITHOUT refreshing. (the user updates Notebook.html, refreshing loses the data they update.)

This partially works however it DOES refresh the page and I lose any data that has been added.

<script>
function openNotebook() {
    window.open('notebook.html', "notebook","width=800, height=600, resizable=yes, top=50, left=10").focus();
}
</script>

<button type="button" class="btn btn-primary" onclick="return openNotebook()">Notebook</button>

Upvotes: 0

Views: 247

Answers (1)

mplungjan
mplungjan

Reputation: 177851

Try this

  • test if you already opened it
  • return false to stop a possible form submission OR use type="button"
  • remove spaces in parameters

var w;
function openNotebook() {
  if (w && !w.closed) w.focus(); // focus if exists and is not closed
  else w = window.open("notebook.html","notebook",
    "width=800,height=600,resizable,top=50,left=10");

  return false; // or preventDefault or make the button type="button"
}

An alternative to testing if w.closed, remove the w from the opener by adding this in notebook.html

window.onbeforeunload=function() { opener.w=null; }

Upvotes: 1

Related Questions