Skip to content
Advertisement

Can you print a page in a function being defined in javascript?

I have (had 2 years ago lol) been working on a web page that prints everything on it, and need to define a function that gets a value, replaces the text box with the value, hides the print button, and prints the page.

<!DOCTYPE HTML>
<HTML>
<head>
<title>KB documents</title>
</head>
<body>
<style>
body {
  text-align:center;
}
</style>
<div id="hidden">
<textarea cols="125" rows="30" id="value"></textarea>
</div>
<button id="button" onclick="print()">print document</button>
<script>
 function print() {
  var value = document.getElementById("value").value;
  document.getElementById("hidden").innerHTML = "<p>" + value + "</p>";
  document.getElementById("button").style.display = "none";
  window.print()
}
</script>
</body>
</html>

It works perfectly–with the exception of printing the page, the most important part.

Thanks in advance.

Advertisement

Answer

Your function print on the top level is overwriting the built-in window.print. Use a different variable name so that window.print does not get reassigned:

<button id="button" onclick="doPrint()">print document</button>
<script>
 function doPrint() {
  var value = document.getElementById("value").value;
  document.getElementById("hidden").innerHTML = "<p>" + value + "</p>";
  document.getElementById("button").style.display = "none";
  window.print()
}

But it would be better to avoid inline handlers, they have way too many problems to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with addEventListener instead.

document.querySelector('#button').addEventListener('click', () => {
  var value = document.getElementById("value").value;
  document.getElementById("hidden").innerHTML = "<p>" + value + "</p>";
  document.getElementById("button").style.display = "none";
  window.print()
});
Advertisement