0

I am using a print element function to print out a view in my SPA. When the view changes the function runs and grabs the view. However, if the user changes something on the page it will not update and when you try to print, you get the same view as it was when the page first loaded. This is the function I'm using:

var printElement = function (elem, append, delimiter) {
    var domClone = elem.cloneNode(true);
    var $printSection = document.getElementById("printSection");

    if (!$printSection) {
        $printSection = document.createElement("div");
        $printSection.id = "printSection";
        document.body.appendChild($printSection);
    }

    if (append !== true) {
        $printSection.innerHTML = "";
    }

    else if (append === true) {
        if (typeof (delimiter) === "string") {
            $printSection.innerHTML += delimiter;
        }
        else if (typeof (delimiter) === "object") {
            $printSection.appendChlid(delimiter);
        }
    }
    $printSection.appendChild(domClone);
};

My question is, can I trigger this function when someone uses the browser print function, such as Ctrl+P so that when they go to print the page, it will be updated?

Jacob Finamore
  • 797
  • 5
  • 19

2 Answers2

1

You can make use of the default javascript events. Since you mentioned you are using jQuery:

$(document).bind("keydown keyup", function(e){
    if(event.ctrlKey && event.keyCode == 80){
        // CTRL+P was pressed.
    }
});
mehulmpt
  • 15,861
  • 12
  • 48
  • 88
  • Thank you Mehul, I give this a +1 but its not exactly a solution to my problem, because a user could be on a mac or they could select the print button on their browser. In this case, the function would not trigger and the user will still be left with the non edited version of the page. I need to be able to trigger the function when the user tries to print. – Jacob Finamore Mar 18 '16 at 16:26
0

I found a solution to my problem, it was answered by another question on stack overflow detect print. This is what I did:

var beforePrint = function () { printElement(document.getElementById("print")); }; var mediaQueryList = window.matchMedia('print'); mediaQueryList.addListener(function (mql) { if (mql.matches) { printElement(document.getElementById("print")); } }); printElement(document.getElementById("print")); window.onbeforeprint = beforePrint;

This covers IE, Chrome, Firefox, and Safari. The beforePrint works for IE and Firefox and matchMedia works for Safari and Chrome.

Community
  • 1
  • 1
Jacob Finamore
  • 797
  • 5
  • 19