Please wait for the window to finish formatting before attempting to print

I'm currently using the javascript code below to pass an element ID to a method. This method then formats that particular ID in a separate window and prints it. However, I've encountered an issue where the print dialogue box opens up before the window completes formatting the new page. As a result, I have to cancel the print dialogue, wait for the page to format, and then initiate the print again. How can I ensure that the page finishes formatting before the print dialogue box opens? Thank you.

function printPartOfPage(elementId) {   
    var printHeader = document.getElementById('header');
    var printContent = document.getElementById(elementId);
    var windowUrl = 'NewWindow';
    var uniqueName = new Date();
    var windowName = 'Print' + uniqueName.getTime();
    var printWindow = window.open(windowUrl, windowName, 'left=20,top=200');
    printWindow.document.write('<html xmlns="http://www.w3.org/1999/xhtml"><head>');    
    printWindow.document.write('<link href='+sURL+'css/style.css rel="stylesheet">');   
    printWindow.document.write('<link href='+sURL+'css/print.css rel="stylesheet">');   
    printWindow.document.write('</head><body>');    
    printWindow.document.write(printContent.innerHTML);
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
}

Answer №1

If you want to delay printing until after the page has finished formatting, one method is to use the setTimeout function.

...
setTimeout(function(){
    printWindow.print();
}, 1)

Alternatively, you can wait for the window to finish loading before initiating the print action:

printWindow.document.addEventListener('load', function(){
    printWindow.print();
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clear out a collection in backbone.js

I am looking to clear out a collection by removing each item in sequence. this.nodes.each(function(node){ this.nodes.remove(node); }, this); The current method is ineffective as the collection length changes with each removal. Utilizing a temporary arr ...

How to use jQuery to extract a particular text from an anchor tag

If I want to choose a specific anchor text and make changes to it, I can do so by targeting anchors with a certain href attribute. For example, on a page with multiple unordered lists, each containing different links: <ul> <li><a href="v ...

A guide on retrieving real-time data from PHP using Ajax

Being new to Ajax, I am struggling to grasp how to retrieve changing variable values from php. Below is the code snippet that I have been working on: <?php $pfstatetext = get_mypfstate(); $cpuusage= cpu_usage(); ?> <div id="show"> <c ...

After attempting to follow a guide, I encountered a scenario where a view was returning None because the is_ajax function was not

After diving into the world of ajax, I encountered a puzzling issue that I can't seem to crack. My hunch is that it involves the comment_id versus the blog_id. (I was following this tutorial: https://www.youtube.com/watch?v=VoWw1Y5qqt8&list=PLKILt ...

Encountered a problem during the installation of tensorflowjs for node | Received an error: Command failed: node-pre-gyp install

While attempting to install @tensorflow/tfjs-node, I encountered the following error: Command failed: node-pre-gyp install --fallback-to-build. Is there a solution to resolve this issue? Below is the complete log: npm ERR! code 1 npm ERR! path E:\ ...

What is the reason behind PHP's json_encode disregarding empty arrays?

Here is my JavaScript code that sends data to a PHP function: <script> var mydata = { id:123, name: 'mike', orders: [] }; $.ajax({ type: 'POST', ...

Using the `ng-repeat` directive as an argument in a Javascript function

I am struggling to pass the ng-repeat element to a JavaScript function, but it's not working as expected. <tr ng-repeat="x in myArry"> <td><input type="text" value="{{x.firstname}}" id="{{x.firstname}}{{$index}}" onblu ...

Unique button for custom "CODE" in Froala

Looking to create a custom button with functionality similar to bold (B) but for source code (Src). I have attempted the following, however it is not fully functional: $("#elm1").editable({ inlineMode: false, minHeight: 300, buttons: ["src"], c ...

Utilizing ARC4 Encryption with Javascript on iOS devices

I keep getting a blank result when running this code. It doesn't display anything. [self.webview loadHTMLString:@"<script src=\"http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/rc4.js\"></script>" bas ...

Enhance toolbox information upon clicking and revert text to its original state when the mouse is moved off

Within my component, I have a property that serves as the tooltip text: @property() copyText = 'Click to copy'; I've managed to create a function using the @click expression to update the text, and also figured out how to revert it back to ...

Preventing default link behavior when a linked element is clicked: A guide

I need help with a link code that I am having trouble with: <a href="page.html" class="myLink"> Link text <div class="toggle">x</div> </a> My goal is to prevent the link from navigating when users click on the x within the tog ...

Manage Blob data using Ajax request in spring MVC

My current project involves working with Blob data in spring MVC using jquery Ajax calls. Specifically, I am developing a banking application where I need to send an ajax request to retrieve all client details. However, the issue lies in dealing with the ...

The perfect way to override jest mocks that are specified in the "__mocks__" directory

Within the module fetchStuff, I have a mock function named registerAccount that is responsible for fetching data from an API. To test this mock function, I've created a mock file called __mocks__/fetchStuff.ts. Everything seems to be functioning corre ...

When trying to locate an item in an array within a VUE application, it may result in

I've got this code snippet that successfully finds the item details in an array: var findGroupId = medias.find(medias => medias.group_name === this.groupName) The medias variable is an array. When I run console.log(findGroupId), I get this result ...

Removing quotes from JSON values in Node.js without removing quotes from JSON keys

For my project, I am currently developing a REST API that utilizes a library called JSONata for data transformation. The API is designed to receive JSON input consisting of both data and mapping information. Below is a simple example: { "map":{ ...

ReactJS is in need of extracting certain values from a promise

Within my Firebase database, I have organized data into two Documents: "users" and "posts". Each post in the "posts" collection is linked to a specific user using their unique id from the "users" collection. My goal is to retrieve user data associated wi ...

Increase the size of the grid system column upon clicking on a Bootstrap icon

I am using Google Maps in a tab with Bootstrap, but the map is too small. I would like to change the Bootstrap grid system when I click on a FontAwesome icon: the first column should turn into col-md-8, and the second column should become col-md-4. Here i ...

Track changes and save only the updated elements in an array

Currently, I am utilizing Angular for the front end, C# for the backend, and an Oracle database for a project with a company. Within the grids provided to me, there are more than 120 records that users can edit individually. My dilemma lies in identifyin ...

Oops! The module "rxjs/Subject" seems to be missing the exported member "Subject"

Here is the code I'm working with: import { Subject } from 'rxjs/Subject'; Upon importing this, an error occurs: rxjs/Subject" has no exported member 'Subject'. I am unable to fix this issue. Does anyone have a solution? ...

The component you are trying to import requires the use of useState, which is only compatible with a Client Component. However, none of the parent components have been designated with the "use client" tag

I encountered an issue with the code snippet below in my Next.js app directory when utilizing useState: When trying to import a component that requires useState, I received this error message. It seems that the parent components are marked as Server Co ...