I want to implement a button to print only a certain div of my page while leaving the possibility to the user of printing the entire page. I am using this code for the print stylesheet which works fine so far: Print <div id=printarea></div> only?
Now what I am doing is including a separate stylesheet that only contains the print configuration as suggested here: https://stackoverflow.com/a/18497062/5775547 , and toggle the stylesheet that contains my @media print in the onclick function of my button:
function handlePrintRouteInstructionsClick() {
routeInstructions.show();
$('link[id="printCss"]').prop("href", "css/printRouteInstructions.css");
window.print();
$('link[id="printCss"]').prop("href", "");
}
The css is included like this:
<link rel="stylesheet" type="text/css" href="" id="printCss" media="print"/>
Now when I press the button, it still prints the entire page. Interestingly, when pressing the button a second time, it works just as expected, printing only the specified div. The dialogue triggered by Ctrl+P still prints the entire page, as it should. Any ideas why this does not work properly on the first button push?