Tony
Tony

Reputation: 193

window.print shows more than once

I have a sample script to print a part of my website page when the button is clicked. But the strange thing is that when I transition use ajax to transition and click the same button window.print activates two times, and if I press 3 times, 3 window.print shows up and it keeps going on and on. How to prevent window.print to show only once even after transitioning to the different page with ajax? Some examples or hints will be great! I would love to here from you!

$(function(){
        $('.printButton').live('click', function(){
            var printPage = $('.printarea').html();
            $('body').append('<div id="print"></div>');
            $('#print').append(printPage);
            $('body > :not(#print)').addClass('print_off');
            window.print();
            $('#print').remove();
            $('.print_off').removeClass('print_off');
        });
    });

Upvotes: 0

Views: 673

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

It seems your event is getting binded again and again to the button. You can try following. Also, use on as live is deprecated.

$('.printButton').off('click');
$('.printButton').on('click', function(){
       var printPage = $('.printarea').html();
       $('body').append('<div id="print"></div>');
       $('#print').append(printPage);
       $('body > :not(#print)').addClass('print_off');
       window.print();
       $('#print').remove();
       $('.print_off').removeClass('print_off');
});

For reference, jQuery.off and jQuery.on

Upvotes: 2

Related Questions