Home > Web Front-end > HTML Tutorial > How to add a button to print an HTML page?

How to add a button to print an HTML page?

王林
Release: 2023-09-13 14:33:02
forward
1839 people have browsed it

How to add a button to print an HTML page?

Add a "Print" button on the HTML web page. When the button is clicked, the entire web page will be printed. This is a fairly simple feature to add to a web page and can be added using a few HTML elements and pure JavaScript.

So let's discuss ways to do this.

method

  • First, add the tag in the HTML dom.

  • Assign its type attribute to "button" and give it some value.

  • Then assign an "onclick" handler to the input that will be handled using JavaScript.

  • The function that handles the input tag click event is as follows -

const handlePrint = () => {
   window.print();
}
Copy after login

The complete code of this method is -

Example

<!DOCTYPE html>
<html lang="en-US">
<head>
   <title>
  	   Adding Print Button
   </title>
</head>
   <body style="color: black;">
      <h1>Hello World!</h1>
      <p>Welcome to my Website</p>
      <p>
         This website is built using plain JS and HTML.
      </p>
      <p>
      Okay Bye!!!
      </p>
      <input value='Print' type='button' onclick='handlePrint()' />
      <script type="text/javascript">
         const handlePrint = () => {
            var actContents = document.body.innerHTML;
            document.body.innerHTML = actContents;
            window.print();
         }
      </script>
   </body>
</html>
Copy after login

The above is the detailed content of How to add a button to print an HTML page?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template