i have problem with this html code,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#div1 {position:fixed;}
#div2 {display:none;}
#div3 {display:none;}
@media print {
#div1 {display:none;}
#div2 {display:none;}
#div3 {display:block;}
}
</style>
</head>
<body>
<div id="div1">
<div>Contents of #div1</div><br/>
<button id="btn1">Go to #div2</button>
</div>
<div id="div2">
<div>Contents of #div2</div><br/>
<button id="btn2">Go to #div1</button><br/><br/>
<button id="btn3">Print</button>
</div>
<div id="div3">Contents of #div3</div>
<script>
$(document).ready(function() {
$("#btn1").on("click",function() {
$("#div1").fadeOut("fast");
$("#div2").fadeIn("fast");
});
$("#btn2").on("click",function() {
$("#div2").fadeOut("fast");
$("#div1").fadeIn("fast");
});
$("#btn3").on("click",function() {
window.print();
});
});
</script>
</body>
</html>
let me tell you what i wish to happen with this code, so, when the page load, it just shows #div1, when i click the #btn1 it hides #div1 and shows #div2, when i click #btn2 it hides #div2 and shows #div1, when i click the #btn3 it prints the page, and it should just show #div3 in the print preview page, but, the problem here is, in the print preview page, it shows #div2 and #div3, i don't know why, i just want to show the #div3 in the print preview page, anyone can help me with this?
2 Answers 2
jquery fadein and fadeout calls changed the precedence of display property so they also appeared ,
add important in your css to override .
Ref: CSS @media print not working at all
Change your styles like below:
@media print {
#div1 {display:none !important;}
#div2 {display:none !important;}
#div3 {display:block;}
}`
Comments
This should also work:
@media print {
#div1 {visibility:hidden; height:0; width:0}
#div2 {visibility:hidden; height:0; width:0}
#div3 {display:block;}
}
$(document).ready(function() {
$("#btn1").on("click",function() {
$("#div1").fadeOut("fast");
$("#div2").fadeIn("fast");
});
$("#btn2").on("click",function() {
$("#div2").fadeOut("fast");
$("#div1").fadeIn("fast");
});
$("#btn3").on("click",function() {
window.print();
});
});
#div1 {position:fixed;}
#div2 {display:none;}
#div3 {display:none;}
@media print {
#div1 {visibility:hidden; height:0; width:0}
#div2 {visibility:hidden; height:0; width:0}
#div3 {display:block;}
}
<div id="div1">
<div>Contents of #div1</div><br/>
<button id="btn1">Go to #div2</button>
</div>
<div id="div2">
<div>Contents of #div2</div><br/>
<button id="btn2">Go to #div1</button><br/><br/>
<button id="btn3">Print</button>
</div>
<div id="div3">Contents of #div3</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>