Open printable image in new window using jQuery

I'm trying to get this seemingly simple jQuery to work. The plan is to have an external image, which is a smaller version of a large ad landing page, opens in a new window with a print dialog and then closes after printing (or canceling). This is the closest I can get it to work ( jsfiddle ):

$('#printBtn').click(function() {
    var couponWindow=window.open('','couponWindow','width=580,height=710');
    couponWindow.focus();
    couponWindow.print();
    couponWindow.close();
});

      

I tried many tries and options to open the image in a new window, including:

var couponWindow=window.open(this.href('http://ecommerce.maurices.com/str/pzTesting/mysteryOffer/coupon.gif'),'couponWindow','width=580,height=710');

      

and

var URL = $.myURL("index", $(this).attr('http://ecommerce.maurices.com/str/pzTesting/mysteryOffer/coupon.gif'));
    window.open(URL,'couponWindow','width=580,height=710');

      

All my attempts to add an image to a window either do not create windows, the window opens and closes immediately, or the window opens with an image but does not display the print dialog. I have a "coupon" image posted outside and also tried with a basic HTML file with an image enclosed in a div. What am I missing?

+3


source to share


2 answers


No need to open a new window. CSS Print Media is all you need.



$("button").on("click", function() {
  $("#coupon").off("load").on("load", function() {
    window.print();
  }).attr("src", "http://www.cdc.gov/animalimportation/images/dog2.jpg");
});
      

body #coupon {
  display: none;
}
@media print {
  body * {
    display: none;
  }
  body #coupon {
    display: block;
  }
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>This will not print</p>
<img id="coupon" />
<button>Print coupon</button>
      

Run codeHide result


+2


source


Create a new HTML file "print-coupon.html" that explicitly invokes the print command and will open this HTML file in a new window.

<img src="http://ecommerce.maurices.com/str/pzTesting/mysteryOffer/coupon.gif" />
<script>
    window.print();
</script>

      



http://jsfiddle.net/hpswddey/

+1


source







All Articles