Utilizing jQuery to Print a Div's Content Along with its CSS styling

Looking for a way to include CSS styles when using this function in my Wordpress plugin that utilizes jQuery to print content from a specific div with the "table_disp" class.

function pop_print(){
    w=window.open(null, 'Print_Page', 'scrollbars=yes');        
    w.document.write(jQuery('.table_disp').html());
    w.document.close();
    w.print();
}

Any thoughts on how to achieve this?

Answer №1

To ensure your pop-up displays correctly, be sure to include the same stylesheet used in the parent page within the pop-up itself. One way to achieve this is by creating a dummy page with your stylesheet and then injecting your HTML content.

var myStyle = '<link rel="stylesheet" href="http://mysite.com/mystyle.css" />';
w.document.write(myStyle + jQuery('.table_disp').html());

Answer №2

function DisplayElement(element) {
    ShowPopup(jQuery(element).html());
}

function ShowPopup(content) {
    var newWindow = window.open('', 'my popup', 'height=400,width=600');
    newWindow.document.write('<html><head><title></title>');
    newWindow.document.write('<link rel="stylesheet" href="http://www.example.com/style.css" type="text/css" />');  
    newWindow.document.write('<style type="text/css">.sample { color: blue; } </style></head><body>');
    newWindow.document.write(content);
    newWindow.document.write('</body></html>');
    newWindow.document.close();
    newWindow.print();                        
}

<a href="#" id="printLink" onclick="DisplayElement('.display_div')">Print</a>

Answer №3

When looking to add a plugin, consider the Jquery printThis plugin as a great option (especially if you're already utilizing jQuery). This plugin aligns perfectly with your requirements. http://plugins.jquery.com/printThis/

The plugin creates an iframe and utilizes your page's CSS while also allowing for a custom CSS file specifically designed for printing purposes, among other useful features.

Answer №4

Include Stylesheet Dynamically

var stylesheet = '<link rel="stylesheet" href="/css/print.css" />';
            var contentToPrint = document.getElementById("printContentID");

            var printWindow = window.open('', '', 'width=900,height=650');
            printWindow.document.write(contentToPrint.innerHTML);
            printWindow.document.head.innerHTML = stylesheet;
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjustable Panel Width

Is there a way to have the width of the bottom panel expand to col-md-12 when the top panel is collapsed, and then return back to col-md-8 when the user expands the top panel again? I'm still learning, but here's what I have managed to code so f ...

Safari's Web Audio API suffering from subpar performance and various shortcomings

For my University project, I am developing an HTML and JavaScript-based mp3 player using the Web Audio API. You can check out the progress of this project by visiting this link: While everything is running smoothly on Firefox and Chrome, Safari is posing ...

Having multiple divs lined up horizontally on a single row

I am trying to create three divs in a single row similar to this: https://i.sstatic.net/A63Sx.png Any assistance on how to achieve this setup would be greatly appreciated. ...

Steps to execute an external Python script in Django by clicking a dropdown button in the HTML

I am trying to set up a Django+Python frontend button that can trigger a Jenkins job. I have created a header with HTML containing a dropdown button. After researching various resources, it seems like AJAX is the way to go for triggering the Jenkins job. C ...

Using jQuery.post to select and manipulate the target div displaying Google search results

I am trying to implement a custom form and display the results in a specific target DIV ('results') using ajax. However, I am facing difficulties and unable to figure out what is going wrong. Even after referring to this demo (https://api.jquery ...

Leveraging the power of AngularJS controllers with jQuery's $.ajax functionality

Is there a way to utilize jQuery's $.ajax() function within an angularJS controller (instead of using angularJS built-in $http) in order to access $scope values from a view/template later? Below is an example of a somewhat minimalistic angularJS cont ...

The outcome of the Python web crawling did not meet our expectations

After using Selenium to scrape web data, I encountered an issue where it only displayed 96 out of 346 products instead of the expected 346. Does anyone have suggestions on how to fix this problem? The crawling code is placed right after the loop for clicki ...

The local sending time from the frontend to the backend automatically adjusts and is reduced by 2 hours

When using the DateTime-local in the HTML field to collect datetime from users, I noticed that when sending it to the backend to create an XML file, the date is automatically subtracted by 2 hours for some reason. Despite not making any alterations, and b ...

Hover over this area to reveal the hidden text as it slides into view

My goal is to hover over truncated text and reveal the full length of the dynamic text. However, I am struggling with removing extra space at the end of shorter text when hovered and displaying all the text for longer ones. I have a solution that almost w ...

Eliminate the jQuery function call in JavaScript

I am working with a file.js that looks like this: // TICautocapture.js var TICautocapture = (function(){ var lib = {...} var error_handler; var handleError = (error_code, error_callback) => {...} function autocapture(container, options){...} ...

Receive the deleted entry upon clicking the thead | Error发

Is there a way to permanently delete a row in a datatable? If I delete all the rows, I would like the datatable to display the default message of "No data available". I have attempted some POST requests : But with no success. DataTables remove row butto ...

What is the best way to include an attribute to an object in a knockout observable array and ensure a notification is triggered?

Implementing Knockout.js in my project, I have an observable array included in the view model. function MyViewModel() { var self = this; this.getMoreInfo = function(thing){ var updatedThing = jQuery.extend(true, {}, thing); ...

Title: How to Build a Dynamic Logo Carousel with React and CSS without External Dependencies

Currently, I am in the process of integrating a logo carousel into my React web application using CSS. My goal is to create a slider that loops infinitely, with the last logo seamlessly transitioning to the first logo and continuing this cycle indefinitely ...

Searching for array keys in JavaScript/jQuery can be done with the indexOf method

I am facing an issue with searching through an array named members. Each element in this array consists of a name as the index (e.g. "John Smith") and an array with "degree" and "id". Here is an example structure: https://i.sstatic.net/bDI2Y.png My searc ...

Issue with JQuery Mobile: Inconsistent page navigation functionality

I am currently utilizing JQuery Mobile along with MVC4. MARKUP: <div data-role="page" data-theme="d" id="main"> <div data-role="header"> <h1>Test Page</h1> </div> <div data-role="content"> & ...

javascript - Alternate text colors several times within specified color ranges

Seeking assistance with changing the text color multiple times from #627CA9 to #FFFFFF and vice versa. Here's what I've tried: function changeColor(id) { var x = document.getElementById(id); if (document.getElementById(id).style.color = " ...

Invoke the controller by clicking inside an iframe using AngularJS

I am attempting to attach an event to an iframe in order to trigger a function in the angular controller whenever any part of the iframe is clicked. My goal is to achieve this using either the jQuery lite provided by angular, or with pure javascript, depen ...

Dynamic rows with a searchable dropdown selection value

My current setup involves using PHP and simple JavaScript to create a searchable dropdown list in dynamically added rows. The issue I am facing is that the searchable dropdown works fine when I add the first row, but it stops working when I add another r ...

Using JavaScript regex to extract the text within a string

I have a specific string that needs to be extracted let str="[a54hy 8:45pm],[f57gh 9:20]" I am looking to retrieve [f57gh 9:20pm] Splitting the string is not an option due to its varying length ...

Accessing the Div id stored in a session parameter

Is there a way to store the id (div id) into a session variable? This is an example of my code below: <div class='fieldRow'>Options </div> <div id="abcde"></div> <div class='Row'> <?php $user_typ ...