What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed document. Here is my current code:

$(document).ready(function(){
    $("#print_req").click(function(){
        $("#print_req").css("display","none");
        window.print();  
    });

    $("#print_req").css("display","block");
    return false;   
});

While this code successfully hides the button during printing, it fails to make the button visible again once the printing is completed. What could be causing this issue?

Answer №1

The approach you are taking is incorrect. Instead of using JavaScript to show and hide the button, or resorting to a background image trick, you should utilize a print stylesheet. By using a print stylesheet, you can apply different styles specifically for when the page is printed. For your situation, you would simply set the display property to none (or visibility to hidden) within this stylesheet.

Begin by adding a stylesheet targeting the media type for print:

<link rel="stylesheet" type="text/css" media="print" href="print.css" />

In the print.css file, include the rule to hide the button:

.printButtonClass{ display : none }

And just like that, the button will be hidden during printing without the need for any JavaScript.

Answer №2

One issue arises from the uncertainty of determining when a print job is complete in JavaScript since there isn't an event that signals its completion.

To enhance security, JavaScript runs within a sandboxed environment in the browser to restrict its access to system resources.

Answer №3

Do it the simple way by adding the noprint class to your button element.

 @media print {
   .noprint{
      display: none !important;
   }
}

Answer №4

The functionality of the print dialog box is integrated into the operating system. Javascript is constrained to interacting with elements within the web page itself, as accessing external resources would pose a significant security risk.

Answer №5

function displayPrintPage() {

var originalPage = document.body.innerHTML;
$('#print-btn').css('visibility', 'hidden'); //hide print button temporarily
var printableContent = document.getElementById("main-content").innerHTML;
document.body.innerHTML = printableContent;
window.print();                    
document.body.innerHTML = originalPage; //restore the original page        
}

Answer №6

Just follow these steps...

When the document is ready:

$('#print').on('click',function(){
  $('#print').hide();
  window.print();
  $('#print').show();

     });
});

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

Node's Object.prototype function returns an empty object

When I run Object.prototype in the browser console, I see all the properties and methods within it. However, when I do the same thing in the NodeJS terminal, I get an empty object {}. Can someone explain why this difference occurs? Attached are screenshots ...

"Incorporating a hyperlink into a newly added table row with the help

When utilizing jQuery, I am able to dynamically add rows to a table with each row containing an anchor tag. However, when attempting to populate the anchor tags with links using jQuery, the links do not appear as expected. Strangely enough, the other data ...

Tips for refreshing a D3.js bubble chart with live JSON data updates

Currently delving into d3 and experimenting with transforming a static bubble chart into a dynamic one that adjusts by removing or adding bubbles based on JSON changes. I am aiming to have the JSON file refreshed every 5 seconds to update the bubble chart ...

Disregard periods in URLs when configuring nginx servers

While developing with Vite in development mode via Docker on my Windows 10 machine, I encountered an issue where the local custom domain would not load due to a required script failing to load. The specific script causing the problem is /node_modules/.vit ...

Perform an asynchronous reload of DataTables using ajax.reload() before calling a function

I need help extracting real-time data from a datatable and populating a form for editing when an edit button is clicked on each row. Despite my efforts, the ajax.reload() function doesn't load the table in time to fill the form with correct data. The ...

Enhance user experience by implementing a feature in AngularJS that highlights anchor

As I am in the process of developing a chat application using Angular, I have encountered an issue with switching between views. One view, named 'chat.html', displays the list of available users while another view, 'chatMessages.html', ...

Using Node.js, we can create a program that makes repetitive calls to the same API in a

My task involves making recursive API calls using request promise. After receiving the results from the API, I need to write them into an excel file. Below is a sample response from the API: { "totalRecords": 9524, "size": 20, "currentPage": 1, "totalPage ...

Managing key presses with functions in VueJs

Within my component, I am utilizing VueStrap's modal in the following manner: <template> <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed=" ...

Obtain a custom token after next authentication through Google login

Utilizing next js, next auth, and a custom backend (flask), I have set up an API Endpoint secured with jwt token. In my next js frontend, I aim to retrieve this jwt token using the useSession hook to send requests to these API Endpoints. Everything functio ...

suggestions for organizing data in an AJAX/jQuery page

Welcome to my JavaScript/Ajax webpage that also utilizes jQuery. I am facing a challenge with displaying a nested structure. Once a top level element is displayed, users should be able to click on it and reveal the levels below (which are dynamically gene ...

Troubleshooting jsPDF problem with multi-page content in React and HTML: Converting HTML to PDF

I need to convert HTML content in my React application into a PDF file. My current approach involves taking an HTML container and executing the following code snippet: await htmlToImage .toPng(node) .then((dataUrl) => { ...

Using ReactJS to create different behavior for checkboxes and rows in tables with Material-UI

I am looking to customize the functionality of checkboxes and table rows. Currently, clicking on a row also clicks the checkbox, and vice versa. What I would like to achieve is for clicking on a row to trigger a dialogue box, and for clicking on the chec ...

Discover the best way to retrieve attribute values using jQuery

I'm struggling to retrieve the value of the attribute "_last_val" from my input, but I'm having trouble getting it. Here is what I have attempted: demo // Here is the HTML code <form method="post" action="" id="feedback_form"> <inpu ...

Implementing CSS keyframes when a specified PHP condition is satisfied

I am looking to implement an opening animation on my website that should only play when a user visits the site for the first time. I want to avoid displaying the animation every time the page is reloaded, so it should only run if a cookie indicating the us ...

Ionic 2: Image source not being updated

When working with Ionic 2, I encountered an issue where the src attribute of an <img> element was not updating inside the callback function of a plugin. Here is the template code: <img [src]="avatar_path" id="myimg" /> After using the Came ...

Issue with XMLHttpRequest.send() not working in Google Chrome when using POST requests

I'm currently developing an application where users can send files using a form through a POST request. As the file uploads, the application makes multiple GET requests to gather information about the upload progress. Interestingly, this functionalit ...

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

What is the process for refreshing a user's session from the backend following updates to their metadata?

Currently, I am utilizing Next.js on the client side, auth0 for authentication, and Django Rest Framework for the backend. By following Auth0's Manage Metadata Using the Management API guide, I successfully managed to set new metadata values (verified ...

React Router version 6.4.5, automatic redirection upon loading the page

Seeking assistance with setting up redirects. Below are snippets of the code. index.js const router = createBrowserRouter([ { //Defining App as the root element... path: "/", loader: () => { }, element: <App/>, ...

Creating a time-limited personal link with Django Rest Framework and React

I have a frontend application built with React Framework that I want to provide access to via a time-limited personal link, without the need for additional authentication functions. With approximately 1-2 new users per day, my proposed implementation is as ...