0

I want to create another window when user clicks open button. This window will contain contents if a div. Also it'll have a close button. On click of the close button I want to close this popped up window.

When we click on open it opens the <div id="myContent">
in another window, but after opening it, I want it to close that window using close button.

document.getElementById("mybtn").addEventListener("click", function() {
  var newWindowContent = document.getElementById("myContent").innerHTML;
  var newWindow = window.open("", "", "width=500,height=400");
  newWindow.document.write(newWindowContent);
});
<article type="text" id="editor" contenteditable="true">
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum ad eos, facere ipsam odio dignissimos voluptatibus dolor sunt qui ipsum, quos praesentium doloribus nulla mollitia laboriosam expedita maxime, asperiores consequuntur?
</article>
<h1>Open the element content when click the button</h1>
<div id="myContent">
  <button id="mybtnn">close</button> This is the content that will be inside the new popup window
</div>
<button id="mybtn">open</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Just use `window.close()` in the click of the button. Also you need to close the document when you have finished writing to it `newWindow.document.write(newWindowContent); newWindow.document.close();` but why not just show a new div in a modal dialog, then you will not have to worry about browsers not allowing a new window – mplungjan Nov 13 '22 at 10:04
  • @mplungjan He needs to close the new window from "inside" of the new window, so it's just window.close – Nikolay Nov 13 '22 at 10:05
  • @Nikolay he ALSO needs to CLOSE the DOCUMENT at time of writing, or the page is in an unstable state. window.close and document.close are not related – mplungjan Nov 13 '22 at 10:06
  • Anyway this is a dupe – mplungjan Nov 13 '22 at 10:07

1 Answers1

0

You can use window.close

<button id="mybtnn" onclick="window.close()">close</button>
Nikolay
  • 10,752
  • 2
  • 23
  • 51