Copy div And his style to new window - javascript

I am trying to copy a div to a new window for printing, That's working fine
but the div his copied without any style attached to it.
$('#PrintNews').bind('click', function () {
var printContents = new $("#divToPrint").clone();
var myWindow = window.open("", "popup", "width=1000,height=600,scrollbars=yes,resizable=yes," +
"toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0");
var doc = myWindow.document;
doc.open();
$(printContents).find("#PrintNews").remove();
doc.write($(printContents).html());
doc.document.close();
doc.focus();
doc.print();
doc.close();
});
});
How can i open that div in a new window for printing, but with all of his styles like in the original div?

you should build the html of new window something like this, to link extarnal css files.
doc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
doc.write("<html>");
doc.write("<head>");
doc.write("<link href='/css/print.css' rel='stylesheet' type='text/css' />"); // your css file comes here.
doc.write("</head>");
doc.write("<body>");
doc.write($(printContents).html());
doc.write("</body>");
doc.write("</html>");

It's because styles had not been loaded before printing.
var showPrintWindow = function (context) {
var printWindow = window.open('', '');
var doc = printWindow.document;
doc.write("<html><head>");
doc.write("<link href='/css/printReport.css' rel='stylesheet' type='text/css' media='print' />");
doc.write("</head><body>");
doc.write(context);
doc.write("</body></html>");
doc.close();
function show() {
if (doc.readyState === "complete") {
printWindow.focus();
printWindow.print();
printWindow.close();
} else {
setTimeout(show, 100);
}
};
show();
};

It depends on the way the div is styled. If the styles are applied based on the ID or class then you should be fine to just include the same stylesheet in the new window. However if any of the styles are based on the element's ancestors then it becomes tricky as you would have to copy the ancestral elements in order for the exact styles to be applied.
It sounds like you ought to be using print-specific styles. You can apply a stylesheet to print only by including the media="print" attribute on the stylesheet link. This stylesheet is then responsible for hiding any elements in the page that you don't want to print and positioning the ones that you do. This way you are not subject to popup blockers and give the user one less step to print the document.
You can achieve the same by using media queries in your original stylesheet. Here is a very simple example:
#media print {
.print {width:100%;}
.noPrint {display:none;}
}
To test this just remove the #media wrapper and see how it looks in your browser. It should give you a pretty good idea of how the page will look on paper.

Include external css into the window to which you are copying your DIV. otherwise only the inline styles will be copied.

Related

Change Twitter Widget appearance on-the-fly

I have the following code in my document:
<a class="twitter-widget" href="url" data-widget-id="138843679974442730">Twitter Timeline</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
data-widget-id is connected to one style. Right now if there is a theme change on the website (I replace all responsible stylesheets and images) everything changes but the Twitter widget.
Since the widget itself is an iframe, I can't change any stylesheets attached to it.
Is there an easy way to change the style of the widget without reloading it (deleting the tag, creating the tag, running js)?
You can style elements in the Twitter widget iframe using JavaScript.
First, you need the active document in the iframe's nested browsing context:
var doc = document.getElementById("twitter-widget-0").contentDocument;
Then, you can apply styles (e.g.):
doc.querySelector(".timeline-header").style["background-color"] = "black";
doc.querySelector(".timeline-header a").style["color"] = "white";
Example: http://codepen.io/smockle/pen/IJHnj
There is no straight forward way of doing this, so I've decided to bring in another dependency that will be delaying the onload event..
<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
And here is the code that did the job:
var twitterBox = document.getElementsByClassName("twitterBox");
if (!twitterBox || twitterBox.length == 0) { return true; }
var twitterTimeline = document.createElement('a');
twitterTimeline.className = 'twitter-timeline';
twitterTimeline.href = 'url';
twitterTimeline.innerHTML = 'Twitter Timeline';
twitterTimeline.setAttribute('data-widget-id', '388742673974046720');
twitterBox[0].removeAttribute('data-twttr-id');
twitterBox[0].innerHTML = '';
twitterBox[0].appendChild(twitterTimeline);
twttr.widgets.load();

Popupwindow image link and to css file

How do I put an image on a pop-up window and link it to a CSS file? Let's say I want to insert an image called big.jpg on my computer. Can this be done by simple Javascript code?
popupWindow.document.writeln('<html><head>');
popupWindow.document.writeln('<link rel="stylesheet" type="text/css" href="tressider.css" />');
popupWindow.document.writeln('</head><body>');
popupWindow.document.writeln('<h2 class="pp">'+help[3].office+'</h2>');
popupWindow.document.writeln('<p></p>');
popupWindow.document.writeln('<h3 >'+'725-0911'+'</h3>');
popupWindow.document.writeln('<p></p>');
popupWindow.document.writeln('<div class="wocao">'+help[3].Description+'</div>');
popupWindow.document.writeln('</body></html>');
popupWindow.document.bgColor="White";
popupWindow.focus();
popupWindow.document.close();
Yes this can easily be done by adding style and img elements into the window directly.
Just use:
var _image = popupWindow.document.createElement('img');
_image.setAttribute('width',#);
_image.setAttribute('height',#);
_image.setAttribute('src',"myimg.png");
popupWindow.document.appendChild(_image);
And do the same for the style tag.
var _style = popupWindow.document.createElement('img');
_style.setAttribute('src',"mystyle.css");
popupWindow.document.appendChild(_style);

Appending Link To Head Of Iframe

I want to append element To head of an Iframe (fancybox)
there is a strange problem : when I use Firefox to Breakpoint on line of code that append element to Head it works correctly but when I run site normally without firebug it does not work;
I am using fancybox 1.3.4 and the code run in onComplete event
var cssLink = document.createElement("link")
cssLink.href = "/themes/furniture/css/test.css";
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
var f123= document.getElementById('fancybox-frame');
var d123= f123.contentDocument || f123.contentWindow.document;
d123.head.appendChild(cssLink);
UPDATE
I also try this code
var $head = $("#fancybox-frame").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: "/themes/furniture/css/test.css", type: "text/css" } ));
but it does not work either
Tnx
Well, it seems to be a racing condition indeed (as pointed out by olsn in his comment) between loading the iframe and finding elements inside of it, which fails if the second occurs first ;)
As a workaround, you could use the .load() method to wait for the iframe to be completely loaded before trying to append the stylesheet to the <head> section.
This code should do the trick :
$(document).ready(function () {
$(".fancybox").fancybox({
"type": "iframe",
"onComplete": function () {
var $style = '<link rel="stylesheet" href="/themes/furniture/css/test.css" type="text/css" />';
$("#fancybox-frame").load(function () {
$(this).contents().find("head").append($style);
});
}
});
});
Note : this is for fancybox v1.3.4. Fortunately v2.x includes more flexible public methods than v1.3.4 to circumvent this issue, like afterLoad and beforeShow
Also notice that setTimeout() will work too, but it renders oddly.

cant print images with JavaScript print function

I am trying to print a report which includes text and images. I am using a javascript function to invoke the print functionality. Everything works well except the images on the page do not show up in the new print window. I have included all the CSS files with it but still my images dont appear in the new print window. Its the same even if I dont include the CSS links.
My javascript function to print is :
function printfun(){
var disp_setting = "toolbar=no,location=no,directories=no,menubar=no,";
disp_setting += "scrollbars=no,left=0,top=0,resizable=yes,width=900 height=650,modal=yes,";
var content_vlue = document.getElementById('<%= tblCharts.ClientID %>').innerHTML;
var docprint = window.open("", "", disp_setting);
docprint.document.write('<html><head>');
docprint.document.write('</head>');
docprint.document.write('<body onLoad="self.print()">');
docprint.document.title = "";
docprint.document.write('<link href="../style/design.css" rel="Stylesheet" type="text/css" />');
docprint.document.write('<link href="../App_Themes/style/graphs.css" rel="Stylesheet" type="text/css" />');
docprint.document.write(content_vlue);
docprint.document.write(tblCharts);
docprint.document.write("</body></html>");
docprint.document.close();
docprint.focus();
}
Are the images background images in the CSS? If so, the browser likely isn't set to print those by default. That'd a browser setting the user would have to change.

append element in head of an iframe using jquery

i want to append a style sheet(css) link to the head of an iframe using jquery .
i tried with the following code but not working.
$('#tabsFrame').contents().find("head").append(cssLink);
i am used to append data to an iframe by using this line of code
$('body', window.frames[target].document).append(data);
In your case, this line would look like this
$('head', window.frames['tabsFrame'].document).append(cssLink);
EDIT:
Add <head></head> to the iframe and change your var cssLink to
cssLink = '<link href="cupertino_1.4/css/cupertino/jquery-ui-1.8.7.custom.css" type="text/css" rel="Stylesheet" class="ui-theme" />
well, you can check with this:
$('#tabsFrame').contents().find("head")[0].appendChild(cssLink);
I believe you can't manipulate the content of an iframe because of security.
Having you be able to do such a thing would make cross-site-scripting too easy.
The iframe is totally seperate from the DOM of your page.
Also, java and javascript are two completely different things!
Follow the Link to see the difference here
This could be related to IE not allowing you to add elements in the DOM, check out the clever solution here
EDIT:
Thanks #kris, good advice to add more info in case links break:
Here is the main code snippet from the link, in case it goes out again.
(This is only needed with some IE version, for the most part, the other answer work just fine)
var ifrm;
//attempts to retrieve the IFrame document
function addElementToFrame(newStyle) {
if (typeof ifrm == "undefined") {
ifrm = document.getElementById('previewFrame');
if (ifrm.contentWindow) {
ifrm = ifrm.contentWindow;
} else {
if (ifrm.contentDocument.document) {
ifrm = ifrm.contentDocument.document;
} else {
ifrm = ifrm.contentDocument;
}
}
}
//Now that we have the document, look for an existing style tag
var tag = ifrm.document.getElementById("tempTag");
//if you need to replace the existing tag, we first need to remove it
if (typeof tag != "undefined" || tag != null) {
$("#tempTag", ifrm.document).remove();
}
//add a new style tag
$("HEAD", ifrm.document).append("");
}

Categories