Miguel Fernandez Miguel Fernandez - 2 months ago 15
Javascript Question

CSS style not showing on print preview

I'm trying to create a function to change my font color but I need to print it, at the moment all it's ok but I'm having problems with the CSS on print, here is my code



$('#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

On snippet works perfect but when I try it in my browser not and on codepen too.

Code not working on CodePen

I'm using Google Chrome. What is the problem and how can I solve it? Thanks in advance.

EDIT

In this picture you can see my problem, When you click a '' element the font color change to red but when you click on print button appears in black, this happen with CodePen code and in my browser but I don't know why works perfectly on Snippet code...

Problem

Answer

This is what you need. Some sites have their own media print so you need to add -webkit-print-color-adjust: exact; to your media print and !important it to make sure it overrides any other media print.

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);
});
Comments