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

Tips for creating a condensed header

As a newcomer to HTML, I am facing challenges in creating a simple header similar to the one displayed on this website or the example in the image below. Below is the snippet of HTML that I have attempted: <header class="header"> <div ...

Adding a CSS class to a Vue component with a custom prop

I am looking to create a custom component in Vue that has the following props: text = the text to display in the link. icon = the identifier of the icon to display next to the link. < sidebar-link text="Home" icon="fa-home"> Below is the .Vue ...

Retrieve the initial class of an element using either jQuery or JavaScript

I need help with a jQuery function that is not working properly. I have 3 anchors with corresponding divs, and when I click on one of the anchors, I want to display the contents of the corresponding div. The anchors are as follows: <a class="home share ...

Unable to Submit Form in JSP Page

I have encountered an issue with a JSP page that contains a form which I am submitting using JavaScript. When the page has a smaller number of items, between 10-50, the submission works perfectly fine. However, when there are around 500 items or more on t ...

When working with create-react-app and TypeScript, you may encounter an error stating: "JSX expressions in 'file_name.tsx' must

After setting up a React project with TypeScript using the CLI command create-react-app client --typescript, I encountered a compilation error when running npm start: ./src/App.js Line 26:13: 'React' must be in scope when using JSX react/r ...

NodeJS loop issue with variable scoping in the context of express and mongoose

My Tech Stack: NodeJS, express, mongoose var i; for(i = 0; i < results.length; i++){ console.log("out: "+i); RegionData.findOne({'rid': results[i].region_id}, function (err, product) { if (product) { console.log("i ...

Styling with CSS and JavaScript: The ultimate method for desaturating multiple images

I am currently designing a portfolio website that will feature desaturated thumbnails of all my work. When you hover over each thumbnail, the color will fade in and out upon mouseover. Since this page will include numerous thumbnails, I have been contempl ...

Having trouble with Ajax retrieving the updated JSON file version

I'm pretty new to coding and terminology in general, so I've done my best to simplify my code, although it might still have redundancies. Appreciate your patience in advance. My task involves using an ajax and php script to write data to a file ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

Feeling lost when it comes to forms and hitting that submit button?

Below is a sample form structure: <html> <head> <title>My Page</title> </head> <body> <form name="myform" action="http://www.abcdefg.com/my.cgi" method="POST"> <div align="center"> <br><br; <br& ...

Using a click event to target the next div and apply a CSS class using Typescript

I am trying to create a Typescript function that will locate the next div and apply a CSS class to it. Here is what I have attempted: <ul> <li><a href="#" onclick="toggle()">Item 1</a></li> <div class="content hide ...

Can a menu with data-toggle='dropdown' remain visible even after clicking on it?

I have a dropdown menu that I created with the use of data-toggle='dropdown'. Everything seems to be working fine as the buttons close the menu upon clicking, except I would like the gray button (as shown below) to keep the menu open. https://i. ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Troubleshooting: Datepicker not appearing in Bootstrap

Here is the detailed markup for the datepicker component: <div class="form-group row"> <div class="col-xs-3 col-md-offset-9"> <label class="control-label">Pick Date</label> <div class="input-group date" id="dp3" data-d ...

Ways to refresh the DOM while making an asynchronous request

Consider the following async function: async function predict_from_model() { $("#loading").html("first update") const model = await tf.loadModel('model.json'); $("#loading").html("second update") //delayed for (var i = 0; i < 100; i++ ...

When implementing Passport-jwt for fetching user data, req.user may sometimes be undefined

No matter how many answers I search for on Stackoverflow or read through the documentation, I still can't solve my problem. Signing in and signing up works perfectly fine - I have my token. But when I try to fetch my current_user using get('/isAu ...

Customizing Geonames JSON Ajax Request

Having found the code I needed from a sample website, I am now seeking help to customize it to only display results from the USA. This is the current code snippet: $(function() { function log( message ) { $( "<div>" ).text( message ).pr ...

JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the me ...

Error: Unrecognized primary operator: $sortby

We have a web application built using Node.js and Mongoose, running on Ubuntu Linux servers hosted on DigitalOcean VPS. One of our Mongoose queries includes a text index with the following operators: less than / equal to limit order by This is how the ...

What is the method for configuring my bot to forward all logs to a specific channel?

const logsChannel = message.guild.channels.cache.find(channel => channel.name === 'logs'); I am looking to set up my bot to send log messages for various events, like member join/leave or message deletion, specifically in a channel named &apo ...