0

I am trying to open a new window with this code and assigning the variables to it, what am I doing wrong?

function writeToDocument() {
  var textColor, backColor, pageTitle;
  var yourText, pageContent, docWindow;

  textColor = prompt("Please enter a text color:", "white");
  backColor = prompt("Please enter a background color:", "black");
  pageTitle = prompt("The page will be titled: ", "Default Title");
  yourText = prompt("Add content to the new document:", "page content");

  pageContent = "<html><head><title>";
  pageContent += pageTitle + "</title>";
  pageContent += "<script>alert('The page ' + document.title + ' was created: ' + 
    document.lastModified) < /script>";
  pageContent += "</head><body><strong>";
  pageContent += "</strong></body></html>";

  var newWindow;

  newWindow = open("", "docWin", "location=1");
  newWindow.document.open();
  newWindow.document.write(pageContent);
  newWindow.document.write(background-color= backColor, color= textColor));
  newWindow.document.close(); // Write your code here
}

I have tried multiple tutorials, but none of the methods worked.

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

You can build your HTML using a template literal string. It will make it easier to see your HTML structure.

The document.title variable will not be available when the alert gets called, so I used pageTitle instead.

function writeToDocument() {
  let textColor, backColor, pageTitle, yourText;

  textColor = prompt("Please enter a text color:", "white");
  backColor = prompt("Please enter a background color:", "black");
  pageTitle = prompt("The page will be titled ", "Default Title");
  yourText  = prompt("Add content to the new document:", "Page content");

  const pageContent = `
    <html>
      <head>
        <title>${pageTitle}</title>
        <style type="text/css">
          body {
            background-color: ${backColor};
            color: ${textColor};
          }
        </style>
        <script type="text/javascript">
          window.addEventListener('DOMContentLoaded', () =>
            alert('The page "${document.title || pageTitle}" was created: ${document.lastModified}')
          );
        <\/script>
      </head>
      <body>
        <h1>${yourText}</h1>
      </body>
    </html>
  `;

  const newWindow = window.open("", "docWin", "location=1");

  newWindow.document.open();
  newWindow.document.write(pageContent);
  newWindow.document.close();
  newWindow.document.title = pageTitle;
}

writeToDocument();
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132