Run JQuery on print dialog or print preview

5.1k Views Asked by At

I'm working on a page with inputs on it that will be printed frequently. When printed, the page requires quite a different layout, with different labels and information presented. To make this simpler, I've got separate CSS for Print and Screen, and labels that correspond to the data from the foreground.

Here's a simplified version of what I'm working with:

<style>
@media screen {
    #testback {display: none;}
    #txtName
    {
        padding: 10px;
        margin: 10px 20px;
        border-radius: 8px;
        border: 2px solid #888;
    }
}

@media print {
    #testfore {display: none;}
    #lblName {
        position: absolute;
        top: 5%;
        right: 25%;
    }
}    
</style>

<div id="testfore">
    <input id="txtName" type="text" placeholder="Name..." />
</div>

<div id="testback">
    <label id="lblName"></label>
</div>

JSFiddle: http://jsfiddle.net/h1vu13p1/1/

I'm hoping to go for a minimalistic approach, where the stuff in the background is only updated when the user decides to print the page, i.e. when the Print Preview or the Print Dialog is brought up. Are there any JQuery triggers that connect to either of those events?

There are about fifteen inputs on the page. If I can't update them when checking the print stuff, and instead have to do it on change/keyup, is there a way to avoid writing a separate function for each input? I was considering using classes, but then I wouldn't know how to get the info to the right labels on the hidden div.

1

There are 1 best solutions below

1
On BEST ANSWER

Can you try this?

window.onbeforeprint = function() {
    $('#lblName').text($('#txtName').val());
};

http://jsfiddle.net/7LL2hwwk/

if you want to solve this with js here you can take a look this:

$('input[id^="txt"]').on('change',function(){
    var name = $(this).attr('id');
    $('#lbl'+name.replace('txt', '')).text($(this).val());
});

http://jsfiddle.net/d5b39w8c/