Reputation: 361
I developed a website with a bunch of print media queries to align stuff when printing the page. when you go to the print mode on web browser, the queries works great. but i want apply/remove those @media print
queries on a regular web page without having to go into the printing mode.(by clicking a button) is there any way to achieve this?
Upvotes: 2
Views: 4178
Reputation: 86
In addition to Boldewyn's answer, if you have @media print
styles inside <style>
tags, you can replace them with @media screen
:
Array.prototype.forEach.call(document.getElementsByTagName('style'), function(style) {
style.innerText = style.innerText.replace(/@media print/gi, '@media screen');
});
See the demo.
Upvotes: 7
Reputation: 3020
First thing that comes to mind is use classes. Simple example to give you the general idea. If you had a button that toggles emulateprint
class on the body you could use eg. this css:
body {
color: black;
}
body.emulateprint {
/* put same styles as @media print in here */
color: red;
}
@media print {
body {
color:red;
}
}
Upvotes: 2
Reputation: 82734
To add to yezzz's answer: If you have the print CSS linked in the HTML like
<link rel="stylesheet" media="print" href="...">
you can remove the media
attribute to enable those styles everywhere, either on the server or with Javascript:
document.querySelector('[media="print"]').removeAttribute('media');
Note, that this doesn't work, if the statements in the print stylesheet are wrapped in a @media print {}
rule.
Upvotes: 4