Establish the default bootstrap theme mode specifically for print formatting

Customizing the theme in Bootstrap is made easy by setting the data-bs-theme attribute on the body or parent element. While this feature is useful, we discovered that printing in light mode produces the best results. Instead of creating an entire set of styles for printing in dark mode, I developed a temporary JavaScript solution that switches to light mode before printing and switches back to the previous mode afterwards.

Although this workaround functions, it does not provide the optimal user experience. In Chrome, the transition between light and dark modes while the print modal is open may be disruptive.

Are there more effective strategies to handle this situation aside from using JavaScript to capture the event or crafting a new set of CSS specifically for printing in dark mode?

Answer №1

Today, I encountered the same issue and was able to resolve it by implementing the following code upon page load. Initially, I tried to listen for print requests (assuming similar to your approach), but after some experimentation, I found that the "preferred-color-scheme" event triggers with a value of "light" when attempting to print. Additionally, I needed to monitor this event to capture user-initiated color scheme changes.

I'm curious to know if this solution works for you as well. I tested it on Edge, Chrome, Firefox, and a few other browsers. I'd be interested to learn if there are any different behaviors in other browsers that may cause this solution to fail.

(() =>
{
    // Identifying the browser's preferred theme
    function GetPreferredTheme()
    {
        // Default to light mode
        var selected_theme = "light";

        // Switch to dark theme if preferred by the browser
        if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches)
        {
            selected_theme = "dark";
        }

        return selected_theme;
    };

    // Setting the theme based on specified input or default to browser's preference
    function SetTheme(theme = "")
    {
        if (theme.length == 0)
        {
            theme = GetPreferredTheme();
        }
        document.documentElement.setAttribute("data-bs-theme", theme);
    };

    // Scheme listener to detect when dark theme is selected
    function SchemeListener(event)
    {
        event.matches ? SetTheme("dark") : SetTheme("light");
    };

    // If window.matchMedia is supported, add listener to toggle themes
    if (window.matchMedia)
    {
        // Add listeners to switch themes when user changes settings
        var scheme = window.matchMedia("(prefers-color-scheme: dark)");
        if (scheme)
        {
            scheme.addEventListener("change", SchemeListener);
        }
    }

    // Display content using the browser's preferred theme
    SetTheme();
})();

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

Issue with Access Denied Error in Internet Explorer 11 when Using AngularJS

Every software development process consists of two essential components. FIRST, the hard work of developing the application. SECOND, the even harder task of making it compatible with the notorious Internet Explorer. Currently, we have an AngularJS (v1.3.1 ...

Is there a way to enable multiple selections in a particular section?

Currently, I am in the process of working on my step by step order and I want to express my gratitude for all the assistance I have received so far. Despite the help, I still have some unanswered questions! The steps in my project are categorized into dif ...

How do I extract a parameter when passing it to a promise in NodeJS?

Let me simplify this query. I need to fetch a parameter used in a promise. Here's the gist of the code: function foo(param) { return fromPromise(blabla, blabla2, param) .then((res) => { return res }).catch((error) => { console.log( ...

What is the best way to achieve complete transparency for an input element?

Is there a way to make the input element completely see-through, allowing the body background image to show through instead of the parent's background color? Sample HTML code: body{ background-image:url("https://upload.wikimedia.org/wikipedia ...

A tutorial on creating circular patterns within a pyramid structure using p5.js and matter.js

I've been attempting to create a pyramid shape using multiple circles, similar to this: balls in pyramid shape To achieve this, I've developed a 'Balls' class: class Balls { constructor(x, y, radius, color, ballCount) { this.x = ...

Customizing a unique dropdown navigation experience

I have very limited experience with using jQuery and CSS. I recently came across the DropIt jQuery plugin files (accessible at ) and decided to integrate it into my Ruby on Rails project. Unfortunately, I am struggling with implementing the "Hover Me" exa ...

Perform an HTTP POST request in Angular to retrieve the response data as a JSON object

I am currently in the process of developing a simple user authentication app. After completing the backend setup with Node.js and Passport, I implemented a feature to return JSON responses based on successful or failed authentication attempts. router.pos ...

Instructions for selecting all checkboxes in an HTML table with just one click

Developing an aspx page with 3 HTML tables, I am dynamically adding checkboxes to each cell. Additionally, I have a checkbox outside each table. When I check this checkbox, I want all checkboxes in the corresponding HTML table to be checked. However, curre ...

Iterating through elements to set the width of a container

I am currently working on a function that dynamically adjusts the width of an element using JavaScript. Here is my JavaScript code: <script> $('.progress-fill span').each(function(){ var percent = $(this).html(); if(per ...

Could someone explain why the window.onload function is not functioning as expected on my other Vue page?

I am facing an issue with my two pages or "views" that have identical JS code. Both pages have a window.onload function where I perform some actions: console.log("loading") window.onload = function() { console.log("loaded") // do stuff } The problem is t ...

Can we leverage map/filter/reduce functions within a promise by encapsulating the result with Promise.resolve()?

Currently, my approach to doing loops inside a promise looks like this: asyncFunc() .then(() => { return new Promise((resolve) => { for (let i = 0; i < length; i++) { // do something if (j == length - 1) { ...

Using Backbone for the front end and Node.js for the backend, this website combines powerful technologies

Currently, I am in the process of developing a new website that will function as a single-page application featuring dialog/modal windows. My intention is to utilize Backbone for the frontend and establish communication with the backend through ajax/webs ...

What is the best way to extract elements from an array object and store them in a separate array using JavaScript

Is there a way to extract specific values from an array object and store them in individual variables as arrays? // Given array const dummy = [ { id: 1, name: 'John', }, { id: 2, name: 'Jane', }, { id: 3, ...

Flickering problems occur when using Jquery to load MVC Views upon hovering

I am trying to create a hover effect that expands and changes the content of each div when hovered over, and reverts back to its original state on mouseout. To achieve this, I am using MVC partial views: (Subpages.cshtml) <div id="subpages" c ...

What is the method for applying a Redux statement?

Experience with Redux toolkits: https://i.sstatic.net/cwu8U.png I've encountered an issue while working with Redux toolkits where I'm unable to access certain statements. I attempted the following code snippet, but it resulted in an error. c ...

Is a shifting background image possible?

Can anyone shed some light on how the dynamic background image on this website is created? Is it a JavaScript plugin, a simple .gif, or something else entirely? Appreciate any insights! ...

Using Flexbox to center items is leading to content overlapping

After attempting to utilize flexbox for centering items, I am encountering issues with content overlapping and misalignment. https://i.sstatic.net/48PMj.jpg Link to the code snippet .footer_3 { position: relative; display: flex; align-items: top; ...

Code in JavaScript often includes the use of variables to store and manipulate data

Do these blocks of JavaScript code serve the same purpose? // First Code Sample var first = prompt("Enter the first number:"); var second = prompt("Enter the second number:"); var sum = Number(first) + Number(second); alert(sum); // Second Code Sample ...

Click on the input field to give it focus before adding a class during the page

Alright, so here's the deal - I have an input field with the class .cf-se-input. I want this field to be focused using jQuery as soon as the document is ready. Additionally, if the field is focused either by the user clicking on it or through jQuery f ...

Selecting a value from a populated dropdown and checking the corresponding checkbox in SQL Server

There are 8 checkboxes in this example: <table style="border-collapse: collapse; width: 100%;" border="1"> <tbody> <tr style="height: 21px;"> <td style="width: 25%; height: 21px;"><strong>Technology</strong& ...