How to print a specific div from an HTML page with custom dimensions

I am looking for a solution to print just a specific div from a website with dimensions of 3"x5". Despite setting up the print button, the entire page continues to print every time.

Is there a way to hide all non-div content in print preview?

CSS

.wholebody {
  height: 289px;
  width: 489px;
  border: 2px solid #00001a;
}

</style>

HTML

<body>

<button onclick="window.print()">Print Page</button>

<div class="wholebody">

</div>

Please advise on any necessary JS functions needed to achieve hiding non-div content. Thank you.

Answer №1

To specify which content to print, you can utilize the @media type print in CSS.

Print: For use with paged material and documents displayed on a screen in print preview mode. (Refer to paged media for formatting specifics related to these formats.)

.wholebody {
  height: 289px;
  width: 489px;
  border: 2px solid #00001a;
}

@media print{
body{
visibility: hidden;
}
div{
visibility: visible; 
}

}
<button onclick="window.print()">Print Page</button>

<p>Content not intended for printing</p>
<div class="wholebody">Print this part</div>

Answer №2

To specify the styles that should be applied when a web page loads, use the @media screen{} block. When the window.print() method is called, the styles within the @media print{} block will take effect. In this instance, clicking on the <button> element will move the newly created element to the publishing page.

var button = document.getElementById('printButton');

printButton.addEventListener('click', function(){  
  var div = `<div style="width:30px;height:50px;border:2px solid black; margin: 20px; display: block;"></div>`;
  $('.wholebody').append(div);
   window.print();
});
@media screen{
  .wholebody {
    height: 289px;
    width: 100%;
    border: 2px solid #00001a;
  }
  
  #printButton{    
    margin-bottom: 5px;
  }
}

@media print{
  #printButton{
    display: none;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <button id="printButton">Print Page</button>

  <div class="wholebody">
  </div>
</body>

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

Simple method to toggle between elements using jQuery

After creating a script using jQuery to show/hide content when tabs are clicked (which also changes the color of the clicked tab), everything is functioning smoothly. However, I believe there may be a more efficient way to switch between content that allow ...

Tips for efficiently waiting for the outcome in a unified function for multiple callbacks within node.js

Perhaps the question title is not the most appropriate, but let me explain what I am trying to achieve in my code // First Callback Function connection_db.query(get_measure_query,function(err,user_data1){ if(err){ // throw err; ...

Struggling with integrating PHP within a JavaScript AJAX function

Here's a button I have: <button id= $id onClick="popup($id)">button</button> I am attempting to use it with an ajax function <script> function popup(id){ alert(" "); document.write(" "); } </script> My goal is to execute P ...

Is it possible to incorporate dynamic variables into the directives of a nested loop? Plus, thoughts on how to properly declare variables in a node.js environment

Question Explanation (Zamka): <----------------------------------------------------------------------------------------------------------> Input Example: 100 500 12 1st Line: represents the left bound (L) 2nd Line: represents the right bound ...

What is the best way to implement my custom toolbar button to utilize the form's validation function within react-admin?

I have developed a unique Toolbar with a custom button that is supposed to mimic the behavior of the standard SaveButton but also perform additional actions after the form is submitted. The form should only be able to submit if it passes validation, and an ...

Guide on passing variables along the promise chain within a Node Express router

Upon reflection, I realized the difficulty of injecting or utilizing a variable inside the Promise scope without a surrounding object or a "this" reference to attach it to. ...

Is it possible to access values from an IndexedDB object store key stored in an array without global access?

I am facing an issue where I am trying to extract values of a specific key from an indexed DB and store them in an array. The array seems to work correctly within the onsuccess function but appears empty after that. It seems like the asynchronous nature ...

Best Practices for Making Remote Requests in Ruby on Rails

Currently, I am creating a Single Page Application using Ruby on Rails for the first time. Although I am still learning, I have set up a side menu with links and a container on the right part of the page to display partial pages. An example of one of my me ...

Are there any other options available in JavaScript to replace the .unload() function?

I have a click event attached to multiple buttons on my page, each loading a different .php file into the same div. The issue arises when the time to load increases after several clicks. $('#start').click(function() { $('#mainbody&apos ...

NodeJS instructs open(html) to execute first before any other code is executed

I am evaluating whether nodeJS is a suitable solution for a project I am working on during my internship. To summarize: I need the basicNode.js file to wait until the open('./basic.html') command has completely opened the browser and loaded its c ...

What is the optimal strategy for incorporating both useLazyQuery and useQuery within the Apollo-client based on specific conditions?

In the navigation menu, I have options for "foods" and "cakes." The Foods page displays a list of all food items url: /foods When the user clicks on cakes, they are redirected to /foods?food=cakes, which is essentially the same page as the foods above. ...

What are the reasons for the failure of an image upload when checked with PHP's is_uploaded_file function?

My html form allows users to upload images, but I'm encountering an issue where the uploaded image fails the "is_uploaded_file" check for some unknown reason. I'm puzzled as to why the upload is failing the is_uploaded_file check. Any ideas? He ...

Invoking WinJS.Binding.List.createFiltered with an asynchronous call to the predicate function

Is there a way to wait for the async operation in this code snippet and use its result as the predicate instead of always returning false? return someList.createFiltered(function(item) { var filter = false; var ...

Troubleshooting issue: Failure in proper functionality of Jquery's slideDown

My form is divided into 3 sections, with the latter two initially hidden using CSS. When users click the next button in the first section, the second section is supposed to slide down into view. However, I'm experiencing an issue where the animation s ...

Error: Collection2 validation did not pass: The field 'name' must be filled in, the field 'email' cannot be empty, and the field 'message' is mandatory

I need to set up a way for visitors to send messages through my website const mongoose = require("mongoose"); mongoose.connect("MongoDb-Connection-Uri") .then(() => { console.log("mongodb connected"); }) .catch(() => { console.log("fail ...

Beware: The use of anonymous arrow functions in Next.js can disrupt Fast Refresh and lead to the loss of local component state

I am currently encountering a warning that is indicating an anonymous object in a configuration file, and even specifying a name for it does not resolve the warning. Below you will find the detailed warning message along with examples. Warning: Anonymous ...

In Vue3, have you ever wondered why the $emit function seems to work fine before a promise fetch,

https://i.sstatic.net/yJmDY.jpg I have encountered an issue while attempting to pass the result of a promise fetch from a child component to a parent component using emit. Strangely, the emit function was working perfectly fine before the $fetch operation, ...

Obtain the text that is shown for an input field

My website is currently utilizing Angular Material, which is causing the text format in my type='time' input field to change. I am looking for a way to verify this text, but none of the methods I have tried give me the actual displayed text. I a ...

Informing the parent window of the child window's activities in order to adjust the timer for the user timeout feature

Within my Jquery function, I have implemented a feature that darkens the screen after a period of user inactivity. This triggers a pop-up window giving the user the option to stay logged in by clicking a button. If there is no response within the set time ...

I am puzzled as to why my ajax script is giving me a 404 error even though the URL appears to be correct

Even though it's not a cross-domain problem, Ajax is returning a 404 error code. In my TIZEN Web application project, I am trying to make an ajax request to a WebService that contains functions necessary for the project. Initially, the xhr.status was ...