I made a script to print just a div, but when I see the preview, it doesn't "format" the page using the CSS added.
HTML Part:
<center>Do not print this</center>
<div>Hi mom!</div>
<center>Print this</center>
<div id="content" class="print">Hi dad!</div>
<input type='button' value='Print' onClick='Print()' />
JS part
function Print(){
var corpo = document.getElementById('content').innerHTML;
var a = window.open('','','width=640,height=480');
a.document.open("text/html");
a.document.write("<html><head><link rel=\"stylesheet\" href=\"./style.css\"></head><body><div class=\"print\">");
a.document.write(corpo);
a.document.write("</div></body></html>");
a.document.close();
a.print();
}
A live version: https://codepen.io/Pop1111/pen/Vwabbzd
It looks like it load the css only AFTER.
Any tips?
Your code will create invalid HTML
Try
function Print() {
var corpo = document.getElementById('content').innerHTML;
const html = [];
html.push('<html><head>');
// assuming the first stylesheet on the parent page - use a different selector if not
// or use +location.protocol+'//'+location.host+'/style.css">'
html.push('<link rel="stylesheet" href="' + document.querySelector("link[rel=stylesheet]").href + '">');
html.push('</head><body onload="window.focus(); window.print()"><div>');
html.push(corpo);
html.push('</div></body></html>');
console.log(html)
/* this will not work in the snippet - uncomment on your server
var a = window.open('', '', 'width=640,height=480');
a.document.open("text/html");
a.document.write(html.join(""));
a.document.close();
*/
}
<html>
<head>
<link rel="stylesheet" href="test.css" />
</head>
<body>
<center>Do not print this</center>
<div>Hi mom!</div>
<center>Print this</center>
<div id="content" class="print">Hi dad!</div>
<input type='button' value='Print' onClick='Print()' />
</body>
</html>
Your new document is unsaved, so does not have your expected path, so the relative reference of the CSS file is not finding the CSS.
To get this to work as expected, you would need to change the CSS reference to absolute reference, or add code to save the new HTML file first.
Is this just how you have tested it, or will your production version function like this as well? (New file, not saved, then print).
You could always inject the actual CSS itself into the head of the new document between style tags, instead of just a reference to the CSS file. Try that.
Related
Image loads correctly in HTML, but not when appended through jQuery.
The project is set up through webpack and images are loaded through file-loader. The code works correctly when directly typed into HTML however, it doesnt work when I attempt to load it through jQuery.
For HTML :
<img src = {require('../images/icon1.png')} className = 'studentIcon' />
For jQuery :
$("#students").append(
$("<div class = 'row'>").append(
$("<div class = 'col-xs-4'>").append(
"<img src = {require('../images/icon1.png')} />"
)
)
)
In HTML the jQuery appended images shows up as:
<img src="{require('../images/icon1.png')}">
with Console error:
icon1.png')%7D:1 GET http://localhost:8080/%7Brequire('../images/icon1.png')%7D 404 (Not Found)
When directly inserted into HTML the images shows correctly, however I have a large number of images which I want to directly attach to some generated code.
You don't need to "nest" many .append() methods like this.
But what you definitely have to do is to concatenate the string (+ sign) with your templating (which runs first), else it's just characters that are part of the string as is.
Here is what you want:
$("#students").append("<div class = 'col-xs-4'><img src = "+{require('../images/icon1.png')}+" /></div>");
And a more "visual/readable" way for the same:
$("#students")
.append("<div class = 'col-xs-4'>"+
"<img src = "+{require('../images/icon1.png')}+" />"+
"</div>");
Would advise the following.
$(function() {
var students = $("#students");
var row = $("<div>", {
class: "row"
}).appendTo(students);
var col = $("<div>", {
class: "col-xs-4"
}).appendTo(row);
$("<img>", {
src: "../images/icon1.png"
}).appendTo(col);
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="students">
</div>
This jQuery creates the various HTML Elements as jQuery OIbjects, appends them as needed, and adds them to the DOM. For the Image Source, it is a relative path to the location on the web server.
Hope that helps.
I am trying to add text to two DIVS with ids= DIV1 and DIV2 in a html page(home.html) from a js page main.js using document.write() command. On clicking the button in html page, the respective text must appear in the hmtl page.
The code is as given below. I keep getting an error: document.write can be a form of eval. Is there a possible way of using document.write() and print the text in the div sections.
HTML code:
<head>
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>
</body>
JAVASCRIPT code:
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.write('<div id="div1">'+"Name:"+ arr.name +'</div>');
document.write('<div id="div2">'+"School:"+ arr.school +'</div>');
}
Name:abc
School:pqrst
...using document.write() command
Don't. Only use document.write during the initial parsing of the page, or to write to a new window you've just opened (or better yet, don't use it at all).
Instead, use the DOM. Example:
function xyz(){
var arr = {name: "abc", school: "pqrst"};
addDiv("name", "Name:" + arr.name);
addDiv("age", "School:" + arr.school);
}
function addDiv(id, content) {
var d = document.createElement("div");
d.id = id;
d.textContent = content;
document.body.appendChild(d);
}
<input type="button" value="click!" onclick="xyz()">
If you have an HTML string you want to insert, you can do that with insertAdjacentHTML, but beware of combining text from an object with HTML, because any < or & in the text must be escaped correctly (more than that if you're going to put the content into an attribute, as with your id values). It happens that your two example values don't have those characters, but you can't assume that in the general case.
You can use insertAdjacentHTML() in place of document.write(). Refer this for more details
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="name">'+"Name:"+ arr.name +'</div>');
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="age">'+"School:"+ arr.school +'</div>');
}
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>
In a.html:
I have a textarea that is converted into a link after the user clicks the submit button. When the user clicks on the link they are redirected to b.html.
<textarea id="sentenceId">
</textarea>
<br>
<button type="button" id="buttonId" onclick="createLink(document.getElementById('sentenceId').value)">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"></a>
</p>
In b.html:
I would like to display the original text.
In script.js:
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
}
If you want to open a new page and get the text there, you could use a post-form and an input[type="hidden"] to send the text and display it afterwards.
If you wand the link to be sendable, you'd either have to encode the text as get-parameter or save it to a database and add the id of the entry to the link.
As #Kramb already mentioned, localStorage is a possibility, but only if you stay on the same browser and both pages have the same domain.
Using localStorage
The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.
a.html
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
localStorage.setItem("textArea", val);
}
b.html
function getText(){
var textVal = localStorage.getItem("textArea");
}
Another option would be to use a query string.
a.html
function navigateTo(val){
window.href.location = "b.html?text=" + val;
}
This will pass the value of the text from textarea with the url during navigation. Once b.html has loaded, you can do the following.
b.html
function getText(){
var url = window.location.href;
var queryIndex = url.indexOf("=") + 1;
var passedText = url.substring(queryIndex);
document.getElementById('foo').value = passedText;
}
This is possible using JavaScript. You can do an AJAX call to another page on you website, and search for an element to get its content. In you're case an textarea
I wrote an example on codepen.io for you. Click here
To make things simpler im using jQuery in this example.
So how does it work?
First of, include jQuery inside the <head> tag of you're website.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
I created the following structure
structure
root
scripts
jQuery.min.js
index.js
index.html
textarea.html
Contents of index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta -->
<meta charset="UTF-8" />
<title>My New Pen!</title>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<!-- Styles -->
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<button id="clickme">To load the textarea content, click me!</button>
<div id="content">The data from the textarea will be shown here, afte you click on the button :)</div>
<!-- Scripts -->
<script src="scripts/index.js"></script>
</body>
</html>
Contents of texarea.html
<textarea id="textarea">
I am the content of the textarea inside the textarea.html file.
</textarea>
Contents of index.js
(function() {
$(document).ready(function() {
/**
* The button which triggers the ajax call
*/
var button = $("#clickme");
/**
* Register the click event
*/
button.click(function() {
$.ajax({
url: "textarea.html",
type: "GET"
}).done(function(response) {
var text = $(response).filter("#textarea").html();
$("#content").append("<br/><br/><strong>" + text + "</strong>");
});
});
});
})()
So what does index.js do exactly?
As you can see i created an Ajax call to the textarea.html file. The .done function holds the response data. The data inside it can be anything depending on the content of the textarea.html file.
$(response).filter("#textarea").html();
The above piece of code filters out the #textarea div and then gets the innerHTML using the jQuery html() function.
If you want to get the value of the textarea through the [value] attribute, you can replace above line to
$(response).filter("#textarea").val();
I believe you want to do this:
function createLink() {
var textvalue = document.getElementById('sentenceId').value;
document.getElementById("link").innerHTML = textvalue;
document.getElementById("buttonId").className ="hideme";
document.getElementById("sentenceId").className ="hideme";
}
.hideme{
display: none;
}
<textarea id="sentenceId">
</textarea>
<br>
<button id="buttonId" onclick="createLink()">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"/>
</p>
I'm trying to create two separate HTML documents: main.html and sufler.html. Idea is to control sufler.html page from main.html . So far I succeeded to write text and change it's font style. But font style changes only ONE time...
I need it to be able to change many times, can't understand what is going on,
because, as I understanding, every time I calling function writing(), I'm clearing all new document's content with newDoc.body.innerHTML = ''... but it seems that not... although text is changing every time.
main.html
<html>
<head>
<script type="text/javascript">
var HTMLstringPage1 = '<!DOCTYPE html><html><head><link href="stilius.css" rel="stylesheet" type="text/css" /></head><body>',
HTMLstringPage2 = '</body></html>',
HTMLstringDiv1 = '<div id="sufler"><div id="mov"><p id="flip">',
HTMLstringDiv2 = '</p></div></div>';
//NEW WINDOW OPEN--------------------------------------------------------------------------------------------------------
var newWindow = window.open('suffler.html','_blank','toolbar=no, scrollbars=no, resizable=no, height=615,width=815');
var newDoc = newWindow.document;
newDoc.write(HTMLstringPage1,HTMLstringDiv1+'Text'+HTMLstringDiv2,HTMLstringPage2);
var script = newDoc.createElement("script");
script.type = "text/javascript";
//=======================================================================================================================
//WRITING----------------------------------------------------------------------------------------------------------------
function writing(){
newText = document.getElementById("sel-1").value.replace(/\n/gi, "</br>");
fontas= document.getElementById("textFont").value;
size= document.getElementById("textSyze").value;
stylas= document.getElementById("textStyle").value;
syntax= document.getElementById("textSyntax").value;
newDoc.body.innerHTML = '';//clears old text (should clear old scripts and functions too)
newDoc.write(HTMLstringPage1,HTMLstringDiv1,newText,HTMLstringDiv2,HTMLstringPage2);//writes new text (and new scripts and functions)
var text = newDoc.createTextNode('document.getElementById("flip").style.font="'+stylas+' '+syntax+' '+size+'px '+fontas+'";');
script.appendChild(text);
newDoc.getElementsByTagName("body")[0].appendChild(script);
}
//=======================================================================================================================
</script>
</head>
<body>
<button type="button" style="background-color: #F5FF25;" onclick="writing()">Apply text</button>
</body>
</html>
Any one node can only be added to the document once. You only define script once but trying to add it to the DOM multiple times. Put the var script = ... line inside writing().
iframe is loaded dynamically into container div inside function.
With cc.text(content); I try to update #code content.
I check changed text in runtime, it's updated but on screen value remains the same.
I am not a javascript pro, so any comments are welcome:
function ShowEditor(content) {
var url = "XmlEditor/Editor.htm";
slHost.css('width', '0%');
jobPlanContainer.css('display', 'block');
frame = $('<iframe id="' + jobPlanIFrameID + '" src="' + url + '" class="frame" frameborder="0" />');
frame.appendTo(jobPlanIFrameContainer);
$(frame).load(function () {
var ifr = frame[0];
var doc = ifr.contentDocument || ifr.contentWindow.document;
var jdoc = $(doc);
var cc = jdoc.contents().find("#code");
// var tst = cc.text();
// alert(tst);
cc.text(content);
});
}
I get the text in commented code, but fail to update #code content.
iframe holds the following html where I omit details inside head and script:
<!doctype html>
<html>
<head></head>
<body>
<form>
<textarea id="code" name="code">some texts</textarea>
</form>
</body>
</html>
Your XML editor doesn't read more than once what's in the textarea.
A simple solution would be to generate in javascript the iframe content with the desired textarea content instead of loading it and then try to change the textarea content.
In fact (depending on the capacities of your XML Editor), you probably can do that directly in a generated text area instead of using a whole iframe to do it.