Basic Programming Tutorials

JavaScript Print

Welcome to the JavaScript tutorial, we have already covered JavaScript Page Redirect and JavaScript Void keyword. Today we will talk about how JavaScript print will let you print the content of the web page. You might have visited a website and tried to keep the content via bookmark or copy source code, but you know that JavaScript print function will let you to equip your website with an extra feature. The user can print the web pages via a real printer.


As a web developer it is important for you to know the importance and use of the JavaScript print function. Later you can apply to your web pages or to the clients as per the need.

JavaScript print – Syntax

The JavaScript print is a function of the object called a window. Let’s see the syntax that a web developer will use to print a web document contents:

Window.print()

Yes, that’s it. Just this syntax will help you to print the web content.

JavaScript Print – Example

Now, we will see the use of the print function to see the real implementation of the JavaScript print method. We have just used a custom function called ‘mySharpLesson()’, once  you will click the ‘ print me!’ button, it will call the ‘mySharpLesson()’ to perform the task.

<html >

<head></head>

<body>

Click the button and get the result.

<button onclick="mySharpLesson()">Print me!</button>

<script>

function mySharpLesson() {

window.print();

}

</script>

</body>

</html>

The out will be seen in two steps, in the first step you will see:

In the second step, when you will click the print me, then you will see:

Now let’s discuss the second result, we used the print function, which will open the print dialog box. There you can check your preferred printing options. In case your printer is not in working condition or not attached. It will show the message like above ‘you need to install a printer’.

Tips to Remember

  • JavaScript print () is supported by the most of the browsers.
  • Print method does not require any parameters to pass.
  • In safer side, ask your reader to enable JavaScript.

Conclusion

We have just seen the use of an object (window) and print () method. The Combination of the both will let you provide your reader more options to remember you for a while. Not to forget thing, just practice what you have learnt at sharplesson. Because it will let you get the perfection and confidence to use JavaScript.