Brandon Alexander Harwood Brandon Alexander Harwood - 3 months ago 9
Javascript Question

Is it possible to bind multiple print buttons in multiple modals to a specific div in each modal?

I'm working on a page through the foundation 5 framework that has a table of information, each one with a link to bring up a specific modal containing detailed information on that specific row. I'm interested in having a "print this information" button for the div contained within each modal. my code is similar to the following:



<div id="detailModal1">
<a href="javascript:window.print()" class="button"></i>Print Modal 1 Info</a>
<div id="printableInfo1">Modal 1 information here</div>
</div>


<div id="detailModal2">
<a href="javascript:window.print()" class="button"></i>Print Modal 2 Info</a>
<div id="printableInfo2">Modal 2 information here</div>
</div>

<div id="detailModal3">
<a href="javascript:window.print()" class="button"></i>Print Modal 3 Info</a>
<div id="printableInfo2">Modal 3 information here</div>
</div>





Hopefully this was specific enough, I appreciate any help. Thanks!

Answer

You can use the @media print css query selector to specify what should appear on the printed page.

In the below example I'm hiding everything on the printed page and then applying a class print-content when a the user clicks a button.

<script type="text/javascript" src="https://code.jquery.com/jquery-git2.min.js"></script>

<style>
    @media print {
        html body * {
            display: none;
        }
        .print-content {
            display: block !important;
        }
        .print-content * {
            display: block !important;
        }
    }
</style>


<div id="detailModal1">
    <a href="#" class="button print-button"></i>Print Modal 1 Info</a>
    <div id="printableInfo1">Modal 1 information here</div>
</div>
<div id="detailModal2" class="print">
    <a href="#" class="button print-button"></i>Print Modal 2 Info</a>
    <div id="printableInfo2">Modal 2 information here</div>
</div>
<div id="detailModal3">
    <a href="#" class="button print-button"></i>Print Modal 3 Info</a>
    <div id="printableInfo2">Modal 3 information here</div>
</div>

<script>

    $('.print-button').click(function(e) {
        var printContainer = $(e.target).parent();
        printContainer.addClass('print-content')
        window.print()
        printContainer.removeClass('print-content')
    })

</script>