Guide to setting a dynamic print style without affecting the screen media

In my report, there is a details section below. The screen provides instructions to view the details with a button that toggles the list's visibility.

When printing the report, I only want the instructions to show if the list is visible. If the list is hidden, I want the instructions to remain hidden as it would be irrelevant on paper and could give the impression that something is missing.

I am unsure how to apply the media-print style within the toggleListVisibility() function. Is it possible to add a class like clsInstructions.addClass(media-print-display-none) or clsInstructions.removeClass(media-print-display-none)?

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

<p>...Main report summary...</p>
<p class='clsInstructions'>See list below for details and suggested actions.</p>
<button type='button' class='noprint' onclick='toggleListVisibility()'>Show / hide list</button>
<div id='myList' style='display:none;'>...details content here...</div>

function toggleListVisibility(){
  $('#myList').toggle();
  if ($('#myList').is(":visible")) {
    //make the instructions visible to the printer...
  } else {
    //make the instructions display:none to the printer, but still visible on screen. how???...
  }
}

Answer №1

Here is a simple way to achieve this:

  1. First, add a common class name to all elements you want to control.
  2. Then, toggle the visibility of these elements as needed.

$(".noprint").toggle(false);
//window.print();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="noprint">A</div>
<div>B</div>
<div class="noprint">C</div>

The use of .noprint in jQuery selects all elements with the class noprint, where . signifies a class selector. This allows you to hide certain elements before printing:

addEventListener('beforeprint', (event) => { 
  $(".noprint").toggle(false);
});

After printing, you can show these hidden elements:

addEventListener('afterprint', (event) => { 
  $(".noprint").toggle(true);
});

In theory, CSS alone could be used for this purpose:

body {
    text-align:center;
}

@media print {
   .noprint {
      visibility: hidden;
   }
}
<h1 class="noprint">DO NOT PRINT THIS</h1>
<h1 class="noprint">PRINT THIS</h1>

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

Enhance your dynamic content with jQuery/AJAX through customized CSS styling

Below is the jquery (3.1.1)/ajax request that I am using: $.ajax({ type: "POST", url: "pref.php", dataType: "text", data: { groupe_id: groupe_id, action: "getProducts" }, cache: false, error: function(html){ ...

What is the ideal way to utilize Vue within the framework of multiple pages?

When using the default Vue CLI setup, Vue is loaded from the index.html page. To work with Vue and dynamic content on the page, everything is typically handled in the App.vue file. But what if you want to make significant layout changes to the page? How d ...

Using Javascript to display or conceal a specific child element within a loop, based on which parent element has been clicked

I need assistance with creating a grid of projects where clicking on a specific 'project' in the loop will display the corresponding 'project_expanded' div, while hiding all other 'project_expanded' divs. My initial plan was ...

Troubleshooting HTML/JavaScript with JSP and JSTL: iPhone only displaying the first option in select dropdown, rather than the selected option

My HTML includes a <select> element: <select id="mySelect"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> ...

Looking to reduce the size of a logo image within a container as you scroll down a webpage?

I've been working on creating a logo section for my website, but I'm struggling to make it shrink as users scroll down and expand back to its original size when they scroll up. I've tried various JavaScript and jQuery functions without succe ...

What is the recommended approach for embedding scripts within Angular templates?

I am working on an Angular SPA that consists of multiple tabs, each served by templates. Depending on the tab, different scripts (both local and CDN) are required. Therefore, I am looking for a way to load these scripts only when they are needed, which mea ...

Unable to determine the reason why the JavaScript plugin is not functioning as expected

I have been attempting to set up a JS modal window and have essentially copied the code for the plugin exactly as instructed, but it is not functioning properly. Here is my code... <!doctype html> <html> <head> <meta charset="utf- ...

Error: Unable to set value on Vuejs key - the target is read-only

Currently, I am utilizing a combination of Laravel9 with Vuejs3. In one of my blade views, I pass PHP variables to a Vue component like so: <subscription-form location="{{ $props['location'] }}" orientation="{{ $props['ori ...

Using JavaScript's DOM manipulation to switch out one HTML tag for another

As a newbie to javascript and DOM, I'm facing an issue with manipulating DOM elements using javascript in the given HTML code. <html> <head> <title>Testing</title> </head> <body> <marquee direction=up heig ...

Effective ways to enable users to upload files in a React Native app

Being in the process of developing a react native app, I am faced with the challenge of allowing users to easily upload files from their mobile devices (pdf, doc, etc). Unfortunately, my search for a suitable native component has proven fruitless. Can anyo ...

Clicking on Google Code Prettify does not trigger syntax highlighting

I utilize Google Code Prettify for syntax highlighting my code. Below is the HTML snippet I use: <head> <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script> </head> <body> ...

How come jQuery is retaining the original DOM element classes even after I have modified them using jQuery?

Here is the code snippet I am working on: $(".drop-down-arrow-open i").click(function(){ console.log("The click function for .drop-down-arrow-open is triggered even when it is closed"); let thisParent = $(this).closest(".projects-container").find(".need ...

Challenges arise with the safari navigation bar within a PWA platform

Struggling with the formatting and spacing issues of a PWA application on IOS devices due to notches and navbar heights. One specific problem is that a chat input with absolute positioning and bottom: 0 does not display properly in Safari because of the n ...

Using jQuery to extract a specific portion of a URL path

Seeking assistance with extracting category information from lengthy URLs and assigning it to a variable. Consider the following URL: http://example.com/community/home/whatever.html The goal is to assign the variable to the folder path that follows /hom ...

Can a single camera be utilized for capturing two different scenes?

Hey there! I'm currently working on rendering two different scenes with a camera that moves in sync between the two. Here's what I'm trying to accomplish: I need to display two separate point clouds in two distinct scenes, but I want the ca ...

Issue with making requests across origins in Vuejs using axios

Currently, I am utilizing Vuejs and axios for handling web requests. So far, I have successfully managed to perform GET, POST, and PUT operations. However, the new challenge that I am facing is uploading media to the server. The server necessitates sending ...

Where can the Path be found for Json inside App Phonegap?

Having some trouble with my Phonegap App! Everything seems to be working fine when I test it in my browser. However, once I compile it into an APK and install it on my phone, it's unable to find the JSON data. I'm a beginner in programming and a ...

Clicking on the initial link will in turn prompt clicks on the subsequent links

Can you please provide instructions on how to correctly simulate a click on the remaining links if a click is made on the first link? jQuery('a.one_num').click(function() { jQuery('a.two_num').click(); jQuery('a.three_num&ap ...

issue with mark.js scrolling to selected sections

Our document searching functionality utilizes mark.js to highlight text and navigate to the results. You can see an example of this in action here. If you search for "Lorem ipsum" -> the highlighting works perfectly, but the navigation jumps to fragmen ...

Is there a way to sort a table using a dropdown menu selection as a filter?

I am currently working on a project that involves a table with three columns, which are typically populated from a SQL database. My goal is to filter the third column based on the value selected from a dropdown menu. I came across a helpful tutorial on W3 ...