Printing doesn't display CSS styling

I am currently working on creating a function to change the font color, however, I am facing issues with the CSS when it comes to printing. Here is the code I have:

$('#draw').on('click', 'p', function () {
   if($(this).hasClass("highlited")) {
      $(this).removeClass("highlited");
   } else {
      $(this).addClass("highlited");
   }
});

$('#click').click(function () {
  var html = "";
  html += '<p>I want to be red...</p>';
  html += '<p>Me too...</p>';
  html += '<p>Ok... Me too...</p>';
  
  $('#draw').html(html);
});
.highlited {
  color: red;
}

@media print {
  .highlited {
    color: red;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="draw">
  <button id="click">Click me</button>
</div>

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

NOTE

The code snippet works perfectly, but I am facing issues when testing it in my browser and on CodePen as well.

Code not working on CodePen

I am using Google Chrome. Can anyone help me identify the problem and provide a solution? Thank you in advance.

EDIT

In the image provided, you can see the issue I am facing. When I click on a '

' element, the font color changes to red. However, when I click on the print button, it appears in black. This issue occurs with both the CodePen code and in my browser, but interestingly, it works perfectly in the Snippet code...

https://i.sstatic.net/MJGrQ.png

Answer №1

Here is the solution you're looking for. Certain websites have customized printing options, so you may need to include -webkit-print-color-adjust: exact; in your print media and use !important to ensure it takes precedence over any other print media settings.

http://codepen.io/anon/pen/JRXEko

<div id="draw">
  <button id="click">Click me</button>
</div>

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

.highlited {
  color: red;
}

@media print {
  .highlited {
    color: red !important;
    -webkit-print-color-adjust: exact;
  }
}

$('#draw').on('click', 'p', function () {
   if($(this).hasClass("highlited")) {
      $(this).removeClass("highlited");
   } else {
      $(this).addClass("highlited");
   }
});

$('#click').click(function () {
  var html = "";
  html += '<p>I want to be red...</p>';
  html += '<p>Me too...</p>';
  html += '<p>Ok... Me too...</p>';

  $('#draw').html(html);
});

Answer №2

The problem lies in the fact that the p tags do not appear on the page until after clicking #click. To resolve this issue, you can try the following code:

$(document).on('click', '#draw p', function () {
if($(this).hasClass("highlited")) {
      $(this).removeClass("highlited");
   } else {
      $(this).addClass("highlited");
   }
});

https://jsbin.com/fetumucero/edit?html,css,js,console,output

Answer №3

Perhaps you could check out the codepen for reference.

Feel free to take a look at this example plnkr:

plnkr.co/edit/NZrYQdGNOntaVwkvK4ZH?p=preview

Thank you!

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

Header, footer, and sidebars are all locked in place, while the central content area is designed for

Using this Demo Template as a starting point, I am looking to create a new layout: However, I am encountering the following challenges: The two sidebars are not properly contained within the scrollable content div. The content div does not have a fixed ...

What is the best way to retrieve the directory path from a FileReader in Java

Hey there, check out these codes I have for reading the file that the user uploads: function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#myImg' ...

Update a single javascript variable on every rotation of the Bootstrap carousel

Within my website, I have implemented a popin/modal feature using Hubspot Messenger which includes a Bootstrap 3 carousel. Each slide of the carousel displays a different "social embed" such as Facebook or Twitter, and I am looking to adjust the width of t ...

Tips for Utilizing CSS Overflow: Hidden to Prevent the Parent Container from Expanding

I have a fixed width column and a fluid column. In the fluid column, I want to display a string with nowrap so that it does not overflow the container. Here is an illustration of how I want the text to appear: --------------------------------------------- ...

Tips for verifying the contents of a textbox with the help of a Bootstrap

I am still learning javascript and I want to make a banner appear if the textbox is empty, but it's not working. How can I use bootstrap banners to create an alert? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&g ...

How can we implement a function on every table using jQuery?

I have created a custom jQuery function for implementing pagination. However, I encountered an issue where when I load the function on a page with multiple tables, the pagination system gets applied to all tables. This means that the number of pages refle ...

Error in Chrome Extension Data Type

I am having trouble adding a highlighted red button to YouTube. The code does not seem to be working as expected. manifest.json { "name": "Example", "version": "0.0", "manifest_version": 2, "c ...

What steps can I take to prompt this function to modify the value of my input?

After recently delving into the world of JavaScript, I decided to create a background color generator that randomly changes when a button is clicked. This simple project involves two input fields (color1 & color2) which receive random values upon clicking ...

Is it not possible to use GLOB with JSHint on Windows operating systems?

Currently, I am experimenting with using NPM as a build tool (). My experience with NPM is limited, and at the moment I only have JSHint and Mocha installed. Attached is my package.json file. However, when I try to run "npm run lint" in the Windows 7 comma ...

Vue.js fails to update view after file status changes

I am currently working with Vue.js and have the following code snippet: <div class="file has-name is-fullwidth is-light"> <label class="file-label"> <input class="file-input" ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

What steps do I need to take to incorporate the Google API into my Chrome extension's content script

I am currently attempting to display labels using the Gmail API within a content script. Below are snippets from my manifest.json and content-script.js files: { "name": "Append Test Text", "description": "Add test123 to body", "version": "1.0", "p ...

The onMessage listener in Chrome consistently returns an 'undefined' response

My latest project involves creating a simple chrome extension that utilizes message passing. The goal of the extension is to listen for messages from a specific website (in this case, localhost:8080/*) and respond with a simple "Bye". To test this function ...

Guide on implementing jQuery WYSIWYG HTML editor on an ASP.net webpage

Currently, I am developing a blogging application and aiming to incorporate the jQuery HTML editor into my ASP.net application. While I am aware of the ASP.net AJAX toolkit editor as an alternative, it is not as lightweight as the jQuery editor. Therefore, ...

What is the best way to retrieve the js window object within emscripten's EM_JS function?

I'm looking to access the window.location in an EM_JS method in order to call a JavaScript method from C++. My attempted approach was: EM_JS(const char*, getlocation, (), { let location = window.location; let length = lengthBytesUTF8(location ...

Exploring the distinctions among different material design frameworks

Confirming my grasp of the situation here. Material design is an interface building approach developed by Google. Material lite is Google's public implementation of this concept. serves as an independent open-source adaptation. In addition, Angul ...

Is it possible to dynamically set the maximumSelectionLength in a select2 dropdown?

In my HTML, I have two select elements. One is for multiple selection of items in a dropdown and the other is for adding tags. If the number of selected items is 3, then users should only be allowed to add 3 tags - no more and no less. $(".js-example-b ...

Email text will be truncated with an ellipsis on two lines

Are there alternative methods to truncate text without relying on webkit-line-clamp? I need to implement this in an email, so using it is not an option. This is the current code snippet I am working with: <style> h2 { line-height:1.5rem; m ...

Discovering the source of a request payload

Is it possible for me to locate the source of a single item in the request payload using Chrome DevTools, even though I am unsure how it was created? Is there any way for me to find this information? ...

The border of the Material UI Toggle Button is not appearing

There seems to be an issue with the left border not appearing in the toggle bar below that I created using MuiToggleButton. Any idea what could be causing this? Thank you in advance. view image here view image here Just a note: it works correctly in the ...