Guillaume
Guillaume

Reputation: 1

How to print one of two sections of a page in javascript

I have two sections on my web page, SectionA and SectionB (2 HTML tables).

I want to be able to print the whole page, only SectionA or only SectionB.

I already have a CSS file with media="print" and I use window.print().

To print the whole page, use your browser print button/menu item.

To print only SectionA :

function PrintSectionA()
{
    $('#SectionA').removeClass('hideFromPrint');
    $('#SectionB').addClass('hideFromPrint');
    window.print();
}

and the opposite for PrintSectionB() Yeah! it works... almost. If I try to print only SectionA, then the whole page, I only get SectionA, because SectionB still has the hideFromPrint class.

What I'd want is :

function PrintSectionA()
{
    $('#SectionA').removeClass('hideFromPrint');
    $('#SectionB').addClass('hideFromPrint');
    window.print();
    $('#SectionB').removeClass('hideFromPrint');
}

But window.print(); returns before the document is sent to the printer. So PrintSectionA() actually prints everything now :( .

Is there a way to make it work?

I think I saw somewhere that I can force a page break in CSS, I could ask the user to print the whole page but only select the 1st or 2nd page... not as fun!

Upvotes: 0

Views: 584

Answers (1)

palswim
palswim

Reputation: 12140

What about defining three functions (with one being "Print All")?

function PrintSectionA()
{
    $('#SectionA').removeClass('hideFromPrint');
    $('#SectionB').addClass('hideFromPrint');
    window.print();
}

function PrintSectionB()
{
    $('#SectionB').removeClass('hideFromPrint');
    $('#SectionA').addClass('hideFromPrint');
    window.print();
}

function PrintAll()
{
    $('#SectionA').removeClass('hideFromPrint');
    $('#SectionB').removeClass('hideFromPrint');
    window.print();
}

Upvotes: 1

Related Questions