Utilizing CSS to showcase various sections of a webpage

Here is a basic example of an HTML file available at this link: http://jsfiddle.net/WhupP/2/ The webpage consists of 4 main sections - header, left-column, righ-column, and footer. Additionally, there are 2 @media elements named screen and print.

When attempting to print the page, only the styles within @media screen{...} are applied, causing the entire page to be printed. It is possible to exclude specific areas such as right-column by adding a class like .noprint {display:none;} to it.

My question is, can individual areas (out of the 5) be printed using CSS alone? If not achievable with CSS and requiring JavaScript, what would be the minimal JS code to achieve this task?

For instance, when printing the page (Ctrl+P or Command+P), I may want to print only area 2 and 3 on one occasion, solely area 2 another time, and just area 4 on a different occasion.

Answer №1

To ensure certain items are visible when printing, use jQuery to assign a class like .visiblePrint before initiating the print action. Toggle this class each time as needed.

If you prefer, you can also capture print requests by utilizing techniques outlined here:

Here's an example:

    <script type="text/javascript">
        $( document ).ready(function() {
            printMode = 1;

                var beforePrint = function() {
                        (printMode==3) ? printMode = 1 : printMode++;
                        console.log('Functionality to run before printing.');
                };
                var afterPrint = function() {
                    $('div').removeClass('visiblePrint');
                    switch(printMode) {
                        case 1:
                            $('#print1').addClass('visiblePrint');
                            break;
                        case 2:
                            $('#print2').addClass('visiblePrint');
                            break;
                        case 3:
                            $('#print3').addClass('visiblePrint');
                            break;
                    }

                    console.log('Functionality to run after printing');
                };

                if (window.matchMedia) {
                        var mediaQueryList = window.matchMedia('print');
                        mediaQueryList.addListener(function(mql) {
                                if (mql.matches) {
                                        beforePrint();
                                } else {
                                        afterPrint();
                                }
                        });
                }

                $(window).on('beforeprint', beforePrint);
                $(window).on('afterprint', afterPrint);

        }());
    </script>
    <style type="text/css" media="print">
        div {
            display:none;
        }
        .visiblePrint {
            display: block;
        }
    </style>
</head>
<body>
    <div id="print1">Printing message 1</div>
    <div id="print2">Second printing message</div>
    <div id="print3">Long live mom</div>
</body>

It's worth noting that this solution is not universally compatible across different browsers. Chrome may raise events twice, while Firefox might not raise any events at all.

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

Can a file be imported into Node.js without the need for packaging?

Is there a way to have an entire file evaluated in node? For example, let's say I want to evaluate the angular.js source file. An example of what the code could look like is as follows: jsdom = require("jsdom").jsdom; document = jsdom("<html>& ...

How can we stop the brief display of a hidden div from occurring?

I have two divs on my webpage - one to display if JavaScript is disabled, and another if JavaScript is enabled. The issue I am facing is that even when JavaScript is not disabled, the div containing the message stating that JavaScript is disabled briefly ...

Determining if a slug is associated with a page in Nextjs 13

Currently, I am working on a dynamic breadcrumb component in Nextjs 13 where I need to use custom values. For example, let's consider the route: /dashboard/[tenant]/[invoice]/editor/abcd. In my Breadcrumb component, I make an API call to retrieve cu ...

Obtaining a compressed file via a specified route in an express API and react interface

Feeling completely bewildered at this point. I've had some wins and losses, but can't seem to get this to work. Essentially, I'm creating a zip file stored in a folder structure based on uploadRequestIds - all good so far. Still new to Node, ...

jQuery.ajax is best described as a technique

Can anyone assist me with defining the jQuery ajax-method as a property of my object? Currently, I have the following ajax request: $.ajax({ type: "POST", url: "../PHP/RoadtripsTable.php", data: ({fnChoice: "listRoadtrips"}) }) I am attempti ...

the functionality of jquery/ajax is not functioning properly

It seems like I am having some trouble with this code. Despite copying and pasting it correctly, the output is going to html-echo.php instead of displaying in htmlExampleTarget Can someone please point out what mistake I might be making here? Thank you, ...

While implementing a delete feature in a CRUD Angular application, why am I encountering a compilation error stating that the property _id does not exist in the array?

Encountering an error while working on a MEAN app with Angular, as the compiler does not seem to accept direct manipulation of the array using the this keyword. Here is an example where the code triggers a compilation error: deleteTodo(todo) { this.t ...

Add elements to an array with express, Node.js, and MongoDB

I'm currently learning about the MERN stack and I'm working on creating users with empty queues to store telephone numbers in E.164 format. My goal is to add and remove these numbers from the queue (type: Array) based on API requests. However, I ...

Functional programming: Retrieve the initial truthy output from executing an array of diverse functions using a particular parameter

As I delve into the world of functional programming in TypeScript, I find myself contemplating the most idiomatic way to achieve a specific task using libraries like ramda, remeda, or lodash-fp. My goal is to apply a series of functions to a particular dat ...

Exploring the possibilities of manipulating the query string with Vue router in vue.js

I've been working on a Vue.js app that includes a tagging feature. I'm looking to implement URL parameters like where users can add tag_ids by interacting with the UI. Although I've successfully managed to update the tag_ids within the app ...

When invoked, a Javascript Object comes back empty

My code snippet: const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results const channelList = channels.each(function (page) { ...

Angular JS: Text with multiple lines and various links

Looking for assistance with integrating multi-line text display in AngularJS? You want to limit the text to 225 characters, add a "view more" hyperlink, and a "less" link to hide extra text. While you've attempted it using jQuery, you're seeking ...

Is there a way to automatically apply a class named "bottom" to the element with the ID "sidebar" when it reaches the bottom of its container?

I have implemented code that adds a CSS class called fixed to the element with ID #sidebar once it reaches a specific distance from the top of the webpage, depending on the page type (e.g. home, single, or page). In a similar manner, I am looking to add a ...

Having trouble setting cookies with Node.js Express?

Check out this code snippet: const app = express(); const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.post("/pinfo", (req, res) => { var form = new formidable.IncomingForm(); form.parse(req, async functi ...

Retrieving blog posts formatted in markdown from a centralized JSON file

My current setup involves using react-markdown to load markdown content from a JSON file. I have opted for a static site hosted on CloudFront to save money and eliminate server operation costs. All posts are compiled into a posts.json file which is then ...

IE is notorious for not playing well with CSS

I am facing an issue with my Google search box code. It works perfectly on Firefox, Chrome, and other browsers except for Internet Explorer. Can anyone help me troubleshoot this? Below is the code snippet: Abulkas Tablet #outerContainer{ width: ...

Is there a way to change a class on an anchor element without disrupting its functionality?

The code snippet provided includes an anchor tag with classes for "window" and "less" applied. Is there a way to eliminate the anchor tag while still keeping the classes intact in the code, ensuring that the functionality remains unchanged? ...

In what way is the JavaScript file able to locate the dependencies following the execution of npm install?

Upon receiving a javascript file named "neededjavascriptfile.js" along with a package.json file, I am faced with the task of running it in an html index file while utilizing certain functions from the javascript file. After executing "npm install --omit=d ...

send the value from the input field to the designated button - link the two buttons

My goal is to create a feature where users can click on a button within the map and open an external page in Google Maps with specific dimensions (500 X 600) and without the Menu bar, Tool bar, or Status bar. // Custom Button Functionality by salahineo ...

React: A Guide to Selectively Targeting the State of List Items

Exploring React, I am currently working on creating a dynamic navigation menu by utilizing the map() function to target the ul and li components efficiently while avoiding code duplication. However, I am encountering an issue where clicking to open one com ...