1

I want to do

$('#foo').insertAfter('#bar');

but only when the user prints the page. I don't want to do any scripting while on screen.

I realize this would have been simple if I wanted to manipulate styles, because then I would have just used @media print {} in CSS. However the goal I am trying to achieve (DOM manipulation) cannot be achieved with CSS, hence I need to use JS.

How can I run JavaScript (or jQuery) only when the user prints or does print-preview?

chharvey
  • 8,580
  • 9
  • 56
  • 95
  • 1
    Related: [detecting-browser-print-event](http://stackoverflow.com/questions/1234008/detecting-browser-print-event) – Razvan Jul 30 '14 at 06:40
  • Surely you could actually insert `foo` after `bar` before and have it only set to `display` in the CSS for `print`? – Rob Schmuecker Jul 30 '14 at 06:57
  • @RobSchmuecker I'm not sure if I understand your question. Before printing, (on screen), `#foo` appears before `#bar`. When printing, I want to reorder the elements such that `#foo` displays after `#bar` rather than before (as on screen and in the source code). – chharvey Jul 30 '14 at 14:20
  • oh right, so `#foo` is already on the page at that point. In which case perhaps look into this http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/ – Rob Schmuecker Jul 30 '14 at 14:25
  • related: [How to trigger javascript on print event?](http://stackoverflow.com/questions/11138939/how-to-trigger-javascript-on-print-event) – chharvey Jul 30 '14 at 14:37

1 Answers1

1

If you do not care about cross browser functionality you can use the window.onbeforeprint event, but it is only supported in IE and firefox 6+

window.onbeforeprint = function(){
     $('#foo').insertAfter('#bar');
};

Another way is to override the CTRL+P keystrokes

window.onkeydown = function(e){
  var char = String.fromCharCode(e.keyCode);  
  if(char == "P" && e.ctrlKey){
      $('#foo').insertAfter('#bar');
  }
};

Fiddle

But this will not work if the user uses the menu system to do a print or right clicks to print.

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87