0

I am trying to print the window. Code for html:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Practising javascript</title>
            <script src="practise.js"></script>
        </head>
        <body>
            <p>Practising javascript</p>
            <button id="submitButton">Print<button>
        </body>
    </html>

Code for javascript:


       let printWindow = () =>{
            window.print();
        }

       document.getElementById('#submitButton').addEventListener('click', () => {
        printWindow();
    })

But when I use onclick on the button and use function with window.print() as the functions body, it works. Why is it so?

MK Camp
  • 3
  • 2
  • I think your question needs more clarity. It is not clear what your problem is or what question you are asking – Sorix May 05 '20 at 16:21
  • '#submitButton' – epascarello May 05 '20 at 16:25
  • The duplicate will explain the ways you can fix your issue with finding the element once you fix the id. – epascarello May 05 '20 at 16:31
  • @Sorix Hello, Thank you for replying. I was practising javascript exercise and there was a question to print contents of the current window (open the print option to print files). And I could not get it done by using the things that I had learnt in my course. So, my question was why did the code that I used did not work. – MK Camp May 06 '20 at 06:06
  • @epascarello Hello, thank you for replying. Before this code I was trying to do it with querySelector(). Thats why the hashtag is there. That's my mistake. But it had not worked with getElementById('submitButton') as well. Anyway, I must have forgot to remove the # while pasting the code here. The answer provided below has worked. – MK Camp May 06 '20 at 06:11

1 Answers1

0

You need to wait for the DOM to load before adding event listeners.

const printWindow = () =>  {
  window.print();
}

window.onload = function() {
  document.getElementById('submitButton').addEventListener('click', () => {
    printWindow();
  });
}