Learn how to hide elements on print pages conditionally in Vue.js using CSS or JavaScript

I am currently using the Vue framework to work on printing webpages for my application. I have an issue that needs a solution, which I will explain below.

<template>

      <div id = "intro" style = "text-align:center;">
        <div
        v-for="report in reports"
        :key="report.property"
        :class="['Section1', { 'non-print-css' : noprint }]">
          <div class="Icon" id="printReport_AId" v-if="isOverview">
             <font-awesome-icon :icon="report.icon" @click="printWindow()"/>
        </div>
      </div>

     <div class="logo"> this text should  be none when printing . if the section1 is none in screen. </div>
      </div>
</template>
      <script type = "text/javascript">
         var vue_det = new Vue({
            el: '#intro',
            data: {
               timestamp: ''
            },
            created() {

            },
            methods: {
              printWindow() {
      const curURL = document.location.href;
      history.replaceState(history.state, '', '/');
      const originalTitle = document.title;
      document.title = '. ';
      window.print();
      document.title = originalTitle;
      history.replaceState(history.state, '', curURL);
    },

     computed: {
       noprint() {
      const printicon = document.getElementById('printReport_AId');
      if (printicon.style.display === 'none') {
        return true;
      }
      return false;
      },
   }

            }
         });
      </script>
<style>
.non-print-css {
  // i have to set the display none for logo when its printed.
}

</style>

There are two div classes:

  1. section1
  2. logo.

The condition is as follows:

  • If section1 is displayed as none, then the logo should not be printed when the page is printed.

    I have added a condition in the computed property to check if the section's display is none. If it is true, it should execute the CSS where we set @print to make the logo display as none.

    I need a proper solution either in CSS or JS.

Answer №1

You can add custom styles for printing by using media queries, like the example below:

@media print {
    .non-print-css {
        display: none;
    }

    .custom-print-style {
        color: blue;
        font-size: 16px;
        text-align: center;
    }
}

Answer №2

  1. "When the display of section 1 is set to none" ... it means that the element is rendered but not visible. In this case, you should use a v-show directive on your section1 instead of using v-if. With v-show set to false, the element will have its CSS property changed to display : none.
  2. "Then, when I print the page, the logo should not be printed"... so if section1's v-show is set to false, we should not print it. In such scenarios, we can create a variable in our data and bind it to section1 (using v-show). When that variable is set to false, the element will not be printed. Let's name this variable isSection1. Here's how you should implement it:
data: {
    isSection1: false, // setting this as false hides section1
    timestamp: ''
  },
  methods: {
    printWindow() {
     // only print if section1 is not hidden
      if (this.isSection1) {
        const curURL = document.location.href;
        history.replaceState(history.state, '', '/');
        const originalTitle = document.title;
        document.title = '. ';
        window.print();
        document.title = originalTitle;
        history.replaceState(history.state, '', curURL);
      }
    }
  }
<div class="section1" v-show="isSection1"> </div>

Answer №3

While exploring solutions for conditionally rendering a component without losing its space when not rendered, I stumbled upon this helpful resource.

Check out this amazing publication that delves into 3 options available in VueJS: here

Answer №4

The issue has been partially resolved, but the element ID is currently null and the event is not being listened to.

  1. Make sure to add the v-bind directive to the logo class.

  2. Include mounted() and computed() methods as shown below.

mounted() {
    window.addEventListener('print', this.noprint);
    },

computed(){
    noprint() {
        const printicon = document.getElementById('printReport_AId');
        if (printicon != 'null') {
          return true;
        }
        return false;
    },
  },

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

Does Node Express call the next middleware immediately when the next function is called?

Can someone please help me grasp the concept of how the next function operates within the Node Express framework? I know that we utilize the next function within the current middleware to trigger the execution of the subsequent middleware listed. These mid ...

Exploring Nodejs and delving into fundamental queries

As I delved into the world of Nodejs, I quickly realized that my knowledge was limited to just being a user. Transitioning to creating my own server posed challenges that were not easily resolved by online tutorials. This led me here seeking guidance to tr ...

What is the best way to incorporate auto-suggestion functionality into a search field using Vue.js without relying on Vue

My current setup looks like this: <div id="app"> <h1>Basic example of typeahead functionality</h1> <input placeholder="Search countries" @input="searchInput" v-model="typeaheadData" /> <ul v-if="!selectedCountry & ...

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

Is it possible to stop an AjaxBehaviorEvent listener or send extra information to the f:ajax onevent function?

In the controller, I have created a listener that looks something like this: public class FooController { public void doSomething(AjaxBehaviorEvent evt) { closeDialogFlag = true; .. if(!isValid){ closeDialogFlag = f ...

Unlock the Potential of Spring REST-JWT-JavaScript for Seamless Transitions

In my Java Spring REST back-end, I am implementing a security feature using Json Web Tokens instead of sessions. For the front-end, I plan to use JavaScript and jQuery for sending requests to the back-end, along with HTML. After a successful login, I stor ...

Using the React UseEffect Hook allows for value updates to occur within the hook itself, but not within the main

I am currently utilizing a font-picker-react package to display fonts using the Google Font API. Whenever a new font is chosen from the dropdown, my goal is to update a field value accordingly. While the 'value' updates correctly within the ...

Adding Information to a Material Design Card

Currently, I am delving into frontend development and honing my CSS skills. In my latest project, I have incorporated a mat card which can be viewed in the linked image https://i.sstatic.net/TEDcg.png. Below is an excerpt of my code: <div class=&quo ...

Differences in behavior of jquery-ajax between Mozilla Firefox and Google Chrome

I am facing a peculiar issue. My current task involves using the Google Maps API to retrieve latitude and longitude data based on zip codes, with the following script: $(document).ready(function(){ $.ajax({ url:"http://maps.googleapis.com/maps/ ...

Avoid changing the regex pattern if it is surrounded by a specific character

I want to change all occurrences of strings enclosed by - with strings enclosed by ~, unless the string is again surrounded by *. For instance, consider this string... The -quick- *brown -f-ox* jumps. ...should be altered to... The ~quick~ *brown -f-ox ...

Unable to properly vertically center multiple divs within a parent div and align their elements vertically within them

I'm diving into the world of HTML/CSS and grappling with various concepts. My goal is to vertically align 2 divs within a larger div, as well as center the contents within those divs. HTML: <html> <head> <link rel="stylesheet" typ ...

personalized styles based on user preferences

My website features a gaming section where users can view quick status updates of their stats using colors like blue, red, and green. I am looking to generate something similar for each user. Here is what I have so far: <style> .box2 { height: ...

What is the best way to align flexbox to the left?

I'm having trouble aligning the FileCard component to the start of the container. I attempted using flex-start in my styling, but the FileCards are still centered. This is the current code snippet: <div v-if="posts" ...

Use $.ajax to display the menu by capturing an array of elements {0}

Whenever I click on one of the DIV elements, a menu pops out on the side displaying more information about the clicked element. I can determine which element I'm clicking on, but I'm struggling to pass that information from jQuery to the PHP pag ...

Generating an HTML table with JSON data in JavaScript

I'm still struggling with JavaScript as a beginner, so please bear with me and provide guidance step by step. Also, try to avoid overwhelming the comments with links as it confuses me. This is an attempt to bypass the CORS issue. <!D ...

Angular 2 eliminates the need for nesting subscriptions

Is there a way to streamline nested subscriptions like the code snippet below? I want to extract values from the subscription for better organization, but using a global variable won't work because the subscription hasn't received the value yet. ...

React.js issue with onChange event on <input> element freezing

I am experiencing an issue where the input box only allows me to type one letter at a time before getting stuck in its original position. This behavior is confusing to me as the code works fine in another project of mine. const [name, setName] = useStat ...

Pictures are automatically adjusted to a resolution of 0 x 0 within the Heroku application

I have encountered an issue with my simple webpage hosted on Heroku. Despite appearing perfectly fine on localhost, 4 images are automatically resized to 0x0 when viewed on Heroku. I am struggling to identify the cause of this problem. Here is how it appe ...

Elemental SVG Animation

I'm currently exploring the world of animating svg objects using CSS. I have successfully learned how to animate a path with: @keyframes stroke_fill { 0% { fill: white; } 50% { fill: white; stroke-dashoffset: 0; ...

React - Children components in an array not updating when props are modified within a callback function

The question may be a bit unclear, so let me provide further explanation. This is a personal project I am working on to improve my understanding of React basics and socket.io. Within this project, I have developed a CollapsibleList component and a NestedL ...