Skip to content Skip to sidebar Skip to footer

Append Stylesheet Link For Printing Triggered On Jquery Click() Event

I have one css link on the head section that has media='screen' attribute, then I want to link the other css file that has media='print' attribute dynamically. and I do this for th

Solution 1:

Maybe you are calling window.print() too early (before the print stylesheet has even been downloaded) - try this:

$("div#alert").click(function(){
    $('head')
    .append("<link rel='stylesheet' href='css/alert.css' media='print' />");
    setTimeout(function() {
        window.print();
    }, 1000);
});

A more elegant solution would be to load the stylesheet asynchronously, insert it in the head, and then call the print() function in the callback of the AJAX request.

Solution 2:

You can use $.get and the success callback in this way:

$("div#alert").click(function(){
    $.get('css/alert.css', function (response) {
       $('head')
          .append("<style rel='stylesheet' media='print'></style>")
          .html(response);

    }).success(function () { 
        window.print();
    });
});

Solution 3:

It looks like your javascript function is running and not letting the browser in to update the CSS.

Watch this video that explains how event loop works in Javasript. That also means that if your cycles work slowly and block the browser, you can just split them in timeouts.

My advice will be doing something like Alex is telling, to put .print in a timeout.

Post a Comment for "Append Stylesheet Link For Printing Triggered On Jquery Click() Event"