Thursday, February 14, 2019

Changing Styles for print media query

I had a situation where I needed to change what would be printed based on what button on the web page the user clicked. Here is an easy way to do that.



<style type="text/css" media="print" id="printStyles">
</style>

<script>
    function printOptionA() {
        var styles = "#optionA {display: block;} #optionB {display:none;}";
        $('#printStyles').text(styles);
        window.print();
    }

 function printOptionB() {
        var styles = "#optionB {display: block;} #optionA {display:none;}";
        $('#printStyles').text(styles);
        window.print();
    }
</script>

The two functions can be called from button, hyperlinks, etc.

If the user just does a Control-P to print in the browser it will print the page as expected (neither of these changes). There is no need to undo these changes after printing.