The problem is that you are registering the "load" event every time you call the
PrintQrCode
function. That means the code within that event will fire for each registered listener. That is, it will stack each time you call the function.
You either need to move the
on
call outside of the function (so it only happens once), or don't use it at all. Given your limited example, I can't see a need to use it all. So give this a try:
self.PrintQrCode = function (obj) {
$('#main').hide();
$('#QrCodePrint').show();
window.print();
$('#QrCodePrint').hide();
$('#main').show();
};
Also, I would suggest you look into CSS media queries for handling what appears during printing. Something like this:
CSS Printing - @media Rule - Tutorialspoint[
^]
After your comment with further code. It looks like you are needing to wait for the image to load before you can print, so I suggest you do something like this:
self.IsPrintQueued = false;
self.GetQrCode = function(obj) {
var ID = obj.Id;
$.ajax({
url: '/QC/GetQrCode',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {
rejectsId: ID
},
success: function(rejectsId) {
self.QrCode(rejectsId.QRCode);
var currentSrc = $("#test").attr('src');
if (currentSrc === rejectsId.QRCode) {
self.PrintQrCode();
} else {
self.IsPrintQueued = true;
$("#test").attr('src', rejectsId.QRCode);
}
}
});
}
self.PrintQrCode = function(obj) {
$('#main').hide();
$('#QrCodePrint').show();
window.print();
$('#QrCodePrint').hide();
$('#main').show();
}
$("#test").on("load", function() {
if (self.IsPrintQueued) {
self.IsPrintQueued = false;
self.PrintQrCode();
}
});
Not sure if that show/hide of main is going to work though... if it doesn't, try using the CSS media rules I linked above.