Preview not showing CSS changes properly

1) I am encountering an issue with displaying CSS in a form preview tab. Despite setting the CSS, it does not reflect on the fields after clicking the preview button.

2) Are there alternative methods to open the tab in a new window rather than opening it directly?

/*form preview*/
function PrintPreview() {
  var toPrint = document.getElementById('from_privew');
  var popupWin = window.open('', '_blank', 'width=1000,height=1000,location=no,left=200px');
  popupWin.document.open();
  popupWin.document.write('<html><title>::Print Preview::</title><link rel="stylesheet" type="text/css" href="Print.css" media="screen"/></head><body>')
  popupWin.document.write(toPrint.innerHTML);
  popupWin.document.write('</div></body></html>');
  popupWin.document.close();
}
@media print{
    input[type="text"],
    input[type="email"] {
      border: 1px solid #000;
      padding: 05px;
      border-radius: 05px;
    }

    input[type="submit"],
    a {
      background: #0088cc;
      border: none;
      border-radius: 05px;
      padding: 08px 25px;
      color: #fff;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="from_privew">
  <form>
    <input type="text" name="name">
    <input type="email" name="email">
    <input type="submit" name="submit">
    <a href="#" onclick="PrintPreview()">Preview</a>
  </form>
</div>

Answer №1

Separate your CSS code into a file named Print.css and remove the @media print section:

input[type="text"],
input[type="email"] {
    border: 1px solid #000;
    padding: 05px;
    border-radius: 05px;
}

input[type="submit"],
a {
    background: #0088cc;
    border: none;
    border-radius: 05px;
    padding: 08px 25px;
    color: #fff;
}

Next, update your JavaScript code to include a reference to the new CSS file:

function PrintPreview() {
    var toPrint = document.getElementById('from_privew');
    var popupWin = window.open('', '_blank', 'width=1000,height=1000,location=no,left=200px');
    popupWin.document.open();
    popupWin.document.write('\
        <html> \
            <head> \
                <title>::Print Preview::</title> \
                <link rel="stylesheet" type="text/css" href="Print.css" media="screen"/> \
                <link rel="stylesheet" type="text/css" href="style.css" media="screen"> \
            </head> \
            <body> \
                <div>')
    popupWin.document.write(toPrint.innerHTML);
    popupWin.document.write('\
                </div> \
            </body> \
        </html>');
    popupWin.document.close();
}

However, whether the page opens in a new window or tab is determined by the browser, so there may not be much you can do about that.

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

What is the best way to handle JSONp response parsing using JavaScript?

I'm relatively new to working with Javascript and I am currently attempting to retrieve data from an External API located on a different website. My goal is to extract the information, parse it, and then display specific parts of it within my HTML pag ...

Issues arise when dealing with a CSS and HTML accordion

I decided to create a CSS and HTML collapsing menu system, also known as an accordion. I found a tutorial on how to do it here. However, I had to make some modifications because I wanted to include images in the 'sections' later on. Instead of us ...

The issue arises when d3.scaleLinear returns NaN upon the second invocation

My journey with d3.js is just beginning and I'm taking it slow. Currently, I'm focused on creating a bar chart where data is loaded from a json file. When I click on the bars, the data changes to another column in the json. This is how my json f ...

Error message: Unable to locate local module in node.js subdirectory

Exploring the folder structure within my application https://i.stack.imgur.com/Pkxpg.png Referring to app_modules/bar and app_modules/foo as local modules Root Folder package.json "dependencies": { "body-parser": "~1.18.2", "cookie-parser": "~ ...

Error: Collection2 validation did not pass: The field 'name' must be filled in, the field 'email' cannot be empty, and the field 'message' is mandatory

I need to set up a way for visitors to send messages through my website const mongoose = require("mongoose"); mongoose.connect("MongoDb-Connection-Uri") .then(() => { console.log("mongodb connected"); }) .catch(() => { console.log("fail ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

Having trouble dynamically adding HTML elements in JQuery

I am dynamically adding HTML elements during runtime using an AJAX call from a JavaScript file. Currently, I am attempting to use a combo box drop-down element to display a list of data. Here is how I am trying to achieve this in my script: $("#myList") ...

Efficiently converting arrays to strings in JavaScript using mapping techniques

My goal is to retrieve data through AJAX without formatting it as JSON, so I took the initiative to encode it myself. The data I am working with consists of client records: where the pound sign (#) separates the client records, the pipe sign (|) separates ...

How does the 'this' variable function when it comes to models in embedded documents?

Being relatively new to node.js and sails, I find it quite easy to work with and enjoy it :) Currently, I am using the sails Framework version 0.10rc3 with MongoDB and sails-mongo. I understand that the contributors of waterline do not particularly like e ...

Customizing Bootstrap Navigation: Creating Space Between Menu Items

I've configured my Bootstrap navigation with a dropdown toggle for "Coverage". I'm looking to decrease the spacing between each list item (li) under this dropdown. What CSS setting should I use to achieve this? Interestingly, when I apply float: ...

What are the reasons to steer clear of setting y.innerHTML equal to x.innerHTML?

If we have a DIV x on the webpage and want to duplicate its contents into another DIV y, we might be tempted to use the following code: y.innerHTML = x.innerHTML; This can also be achieved using jQuery: $(y).html( $(x).html() ); However, it is recommen ...

Error: Unable to access undefined properties (reading 'url')

I am currently working on creating a drag-and-drop card game and I have encountered an issue with the react-dnd library. When using data from the file, everything works fine, but if I have to fetch the data externally, it throws an error. This problem see ...

Enhance your Next.js application with beautifully styled formatting using prettier

Looking for some assistance in setting up prettier with my next.js project. I have the following configuration defined in my package.json file: "scripts": { "format": "prettier --write \"**/*.{js, jsx}\"", }, My project structure includes sever ...

Refreshing a webpage post initial loading using Next.js

Having trouble with my checkout route ""./checkout"" that displays embedded elements from Xola. The issue arises when using client-side routing as the checkout page requires a manual refresh to load correctly and show the Xola elements on the DOM ...

Executing JavaScript with Python in Selenium

Completely new to Selenium. I need help running a javascript snippet in this code (as commented), but struggling to do so. from selenium import webdriver import selenium from selenium.common.exceptions import NoSuchElementException from selenium.webdriver ...

Is there a way to customize the selected option in the autocomplete feature of Material UI components?

Is it possible to customize the CSS of selected options in Material UI autocomplete? Can this be achieved by utilizing the theme? ...

Is conditional CSS possible with NextJS?

While working on an animated dropdown for a navbar, I came across this interesting dilemma. In a strict React setup, you can use an inline if/else statement with onClick toggle to manage CSS animation styles. To ensure default styling (no animation) when ...

Every time I try to restart my React Project, it seems to encounter strange issues that

Currently, I am following a fullstack React tutorial which you can find here: React Tutorial I have encountered an issue where every time I close my laptop and reopen the project, npm start throws a strange error. Initially, I tried to fix it by starting ...

Guide on how to modify a static css file using Node.js

Issue Whenever a user updates the theme on the front-end, my Node.js API needs to update the static CSS file located in a public folder set up by Express. This way, when pages are served again with <link href="public/theme.[userId].[hash].css", the use ...

Paste the current webpage's URL into a fresh alert popup using javascript"

I found myself spending hours trying to figure out the best way to create a JavaScript function that would copy the current URL and display it in a new alert window. Imagine a scenario where a user clicks on "Share this page" and a new alert window pops u ...