JS - print only <div> from another file - javascript

Now I'm using onClick="window.print(); return false;"...
But I need to print a div content form another file.
Example:
I have the file buttons.html, but in this file is my print button with window.print().
I need when this button is pressed to print only div content (e.g. div id=...), but from the file index.html.
I hope you understand me.
*Please give more detailed code, I'm new.
Thanks!

function printDivs()
{
var divs = document.getElementsByTagName("div");
var text = "";
for( var i=0; i<divs.length; i++ )
{
var div = divs[i];
if (typeof(div.nodeName) !== "undefined")
{
text = text + div.innerHTML + "<br /><br />";
}
}
document.body.innerHTML = text;
window.print();
}
That should work, as long if its executed on the same page. Is this what you mean or do you mean something else?
You can call this script by using: Print for example.

That's unusual, but certainly possible:
// buttons.html, Using jQuery
$('button').click(function() {
$.get('index.html', function(h) {
$('body').html($('div#content', h).html());
window.print();
}, "html");
});

Related

output specific data from div and print it via printer

I've spent all day in getting a solution for my need but since i'm not an experienced coder it's time for me to ask you guys for a little help.
My scenario is:
I have some php code like:
<div id="unique_name">
<?php function_show_qrcode()?>
<?php function_show_text1()?>
<?php function_show_text2()?>
<?php function_show_text3()?>
</div>
What i want to achieve is to print the content of "unique_name" div (qrcode and some additional info) directly to a label printer attached via wireless on my smartphone and PC, printer that prints on continuous paper with a width of 62mm.
I have tried a lot of codes that i found but with no success because of browsers behavior regarding window.print()
The following code is working on firefox and chrome on pc but it is not working on safari mobile
<script>
function printDiv(unique_name) {
var printContents = document.getElementById(unique_name).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
Print label
I am stuck on that and i think that something like converting the content of unique_name div into an image, save it and print it after that should work but there are a lot of steps to do and we want to do it more easy something like click and print or click and popup and then print and the most important thing is that it needs to work on mobile browsers
Thank you in advance!
try this :
<script>
function printDiv(myId){
var HiddenElements = document.querySelectorAll( 'body *' ); // get all the elements in the body
var VisibleElements = document.querySelectorAll( '#' + myId + ' *' ); // gets the elements inside the div to be printed
var index = 0, length = HiddenElements.length;
for ( ; index < length; index++) {
HiddenElements[index].style.visibility = "hidden"; // hide all the elements in the body
}
index = 0;
length = VisibleElements.length;
for ( ; index < length; index++) {
VisibleElements[index].style.visibility = "visible"; // show all the elements inside the div to be printed
}
// display the element to be printed
myElement = document.getElementById(myId);
myElement.style.visibility = "visible"
var oldPos = myElement.style.position;
myElement.style.position = "absolute";
myElement.style.left = 0;
myElement.style.top = 0;
setTimeout(window.print, 1000); // Wait a bit for the DOM then Print ( Safari :/ )
// wait for the data to be sent to the printer then display the previous content
setTimeout(function(){
index = 0;
length = HiddenElements.length;
for ( ; index < length; index++) {
HiddenElements[index].style.visibility = "visible";
}
myElement.style.position = oldPos;
}, 5000);
}
</script>
Print label
JsFiddle : https://jsfiddle.net/2m5ha1ta/67/
i don't know why on JsFiddle the onclick doesn't work, so i added an id to the a and added an eventListener to it and it's working ( check the fiddle )
i don't know why exactly but apparently in Safari , Window.print is executed before the DOM is manipulated,
try putting the window.print() in a timeout:
replace this line window.print(); with setTimeout(window.print, 1000);
give it some time to print, then put back the original content :)
setTimeout(function(){
document.body.innerHTML = originalContents;
}, 2000)
you can play with the timeout's number of milliseconds until you get the sweet spot, it doesn't have to be 2000.

Javascript pulling content from commented html

Bit of a JS newbie, I have a tracking script that reads the meta data of the page and places the right scripts on that page using this:
var element = document.querySelector('meta[name="tracking-title"]');
var content = element && element.getAttribute("content");
console.log(content)
This obviously posts the correct tag to console so I can make sure it's working .. and it does in a test situation. However, on the actual website the meta data i'm targeting is produced on the page by a Java application and beyond my control, the problem is it is in a commented out area. This script cannot read within a commented out area. ie
<!-- your tracking meta is here
<meta name="tracking-title" content="this-is-the-first-page">
Tracking finished -->
Any ideas appreciated.
You can use this code:
var html = document.querySelector('html');
var content;
function traverse(node) {
if (node.nodeType == 8) { // comment
var text = node.textContent.replace(/<!--|-->/g, '');
var frag = document.createDocumentFragment();
var div = document.createElement('div');
frag.appendChild(div);
div.innerHTML = text;
var element = div.querySelector('meta[name="tracking-title"]');
if (element) {
content = element.getAttribute("content");
}
}
var children = node.childNodes;
if (children.length) {
for (var i = 0; i < children.length; i++) {
traverse(children[i]);
}
}
}
traverse(html);
One way is to use a NodeIterator and get comment nodes. Quick example below. You will still need to parse the returned value for the data you want but I am sure you can extend this here to do what you want.
Fiddle: http://jsfiddle.net/AtheistP3ace/gfu791c5/
var commentedOutHTml = [];
var iterator = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT, NodeFilter.FILTER_ACCEPT, false);
var currentNode;
while (currentNode = iterator.nextNode()) {
commentedOutHTml.push(currentNode.nodeValue);
}
alert(commentedOutHTml.toString());
You can try this. This will require you to use jQuery however.
$(function() {
$("*").contents().filter(function(){
return this.nodeType == 8;
}).each(function(i, e){
alert(e.nodeValue);
});
});

Google Apps Script - Move Cursor onclick

I would like to implement a Table of Contents in the sidebar of a Google Docs document which will take you to the appropriate sections when clicked. I am generating the HTML for the sidebar element by element, and I see that there is a moveCursor(position) function in Document class, but I can't see how to actually call it using onclick. Not the full code but shows the problem:
function generateHtml() {
var html = HtmlService.createHtmlOutput('<html><body>');
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
//Iterate each document element
var totalElements = body.getNumChildren();
for(var i = 0; i < totalElements; ++i) {
var element = body.getChild(i);
if(element.getType() == DocumentApp.ElementType.PARAGRAPH) {
var text = paragraph.getText();
if(text.trim()) { //Not blank paragraph
var position = document.newPosition(element, 0);
/**Would like to have <a onclick=document.moveCursor(position)> here**/
//Show first 20 chars as preview in table of contents
html.append('Detected paragraph ')
.append(text.substring(0, 20))
.append('<br />');
}
}
}
html.append('</body></html>');
return html;
}
How can I accomplish this in Apps Script? The code can be completely restructured as needed.
This line:
/**Would like to have <a onclick=document.moveCursor(position)> here**/
Change to:
<div onmouseup="myClientFunction()">Text Here</div>
Add a <script> tag to your HTML:
<script>
var valueToSend = code to get value;
window.myClientFunction = function() {
google.script.run
.myGsFunctionToMoveCursor(valueToSend);
};
</script>
Then you need a myGsFunctionToMoveCursor() function in a script file (.gs extension)
function myGsFunctionToMoveCursor(valueReceived) {
//To Do - Write code to move cursor in Google Doc
. . . Code to move cursor
};

How to dynamically create list of <a> tags using js

I am creating html page which needs to create a list of links dynamically on a click of button. I know how to create this list when number of links to be created is known before like this:
//For 4 tags:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.innerHTML = "link1 text";
aTag.setAttribute('onclick',"func()");
mydiv.appendChild(aTag);
var bTag = document.createElement('b');
bTag.innerHTML = "link2 text";
bTag.setAttribute('onclick',"func()");
mydiv.appendChild(bTag);
var cTag = document.createElement('c');
cTag.innerHTML = "link3 text";
cTag.setAttribute('onclick',"func()");
mydiv.appendChild(cTag);
var dTag = document.createElement('d');
dTag.setAttribute('onclick',"func()");
dTag.innerHTML = "link4 text";
mydiv.appendChild(dTag);
But the problem is that the count will be known at run time and also on function call i need to identify the id of link that invoked function.. Can anybody help?
I don't know weather you receive or not the HTML to be shown in the anchor, but anyway, this should do the work:
function createAnchor(id, somethingElse) {
var anchor = document.createElement('a');
anchor.innerHTML = "link" + id + " text";
anchor.setAttribute("onclick", "func()");
return anchor;
}
Then you call the function like this:
function main(num_anchors) {
var mydiv = document.getElementById("myDiv");
for (var i = 0; i < num_anchors; i += 1) {
mydiv.appendChild(createAnchor(i));
}
}
Of course this code can be improved, but this is just for show how can this be possible.
Yes it is possible to do this at runtime .
JQuery provides very useful dom manipulation . So you can traverse the dom , filter what you need ..
you can find a lot of useful functions here .
http://api.jquery.com/category/traversing/
It would look something like this.
$( document ).ready(function() {
$( "a" ).each(function( index ) {
// enter code here..
}
});
document.ready gets invoked once the DOM has loaded.

How to change an HTML Link Value using JavaScript?

I have an HTML page where I want to change Image & Link with at regular interval of time.
I have following code in Head Tag :
<sctipt>
var slideimages=new Array()
var slidelinks=new Array()
var text = document.getElementById('slidetext')
function slideshowimages(){
for (i=0;i<slideshowimages.arguments.length;i++){
slideimages[i]=new Image()
slideimages[i].src=slideshowimages.arguments[i]
text.innerHTML = textChange.aruguments[i]
}
}
function slideshowlinks(){
for (i=0;i<slideshowlinks.arguments.length;i++)
slidelinks[i]=slideshowlinks.arguments[i]
}
function gotoshow(){
if (!window.winslide||winslide.closed)
winslide=window.open(slidelinks[whichlink])
else
winslide.location=slidelinks[whichlink]
winslide.focus()
}
</script>
And Following Code in Body Tag :
<script>
slideshowimages("D:/Search/images/back1.jpg", "D:/Search/images/back2.jpg", "D:/Search/images/back3.jpg","D:/Search/images/back4.jpg","D:/Search/images/back5.jpg","D:/Search/images/back7.jpg")
slideshowlinks("http://wsabstract.com", "http://dynamicdrive.com", "http://java-scripts.net","http://stackoverflow.com","http://superuser.com","http://serverfault.com")
textChange("wsaabstract","dynamicdrive","java-script","stackoverflow","superuser","serverfault")
var slideshowspeed=3000
var whichlink=0
var whichimage=0
function slideit(){
if (!document.images)
return
document.images.slide.src=slideimages[whichimage].src
document.getElementById('slidetext').innerHTML=text.value
whichlink=whichimage
if (whichimage<slideimages.length-1)
whichimage++
else
whichimage=0
setTimeout("slideit()",slideshowspeed)
}
</script>
The Images are changing regularly but only when I have not used the text label that is "slidetext" (which is also hyperlink). But, Using text label, image & text become steady. So, what should be modification to change image & text at regular interval.
text.innerHTML = textChange.aruguments[i]
Normal the fault in your code ?

Categories

Resources