Adding CSS to new document created by Javascript - javascript

I'm trying to create a blank document with Javascript, and then import the CSS file I already have with it.
Here is my code:
function printData() {
let ptimetable = document.getElementById("timetable");
let printWin = window.open("");
printWin.document.write(ptimetable.outerHTML);
let hd = printWin.document.getElementByTagName("head")[0];
let link = printWin.document.createElement("link")
link.rel = "stylesheet";
link.type = "text/css";
link.href = "../css/main.css";
hd.appendChild(link);
//printWin.print();
//printWin.close();
}
I can't figure out what I'm doing wrong - the document is created, but the CSS from my file doesn't apply to the table.
Any help would be much appreciated!
Thanks!
R

After the comments I've seen, the problem resides in the incorrect CSS link. There's also an issue with one of the functions that I have seemingly just made up in my head. Thanks everyone

Related

Trying to add css styling to iframe with JavaScript

Trying this on Wordpress:
Inside my iframe I have a ._2p3a class I want to change its width to ._2p3a {width: 100% !important;}.
With CSS its not possible to access that class so I am trying with JavaScript:
MY JS CODE:
function hello() {
let myiFrame = document.getElementById("iframe-css");
let doc = myiFrame.contentDocument;
doc.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';
}
//the iframe id > "iframe-css"
code Source: https://redstapler.co/how-to-apply-css-to-iframe/
The error:
land_page.js?ver=1.0:4 Uncaught TypeError: Cannot read property 'body' of null
at hello (land_page.js?ver=1.0:4)
at HTMLIFrameElement.onload ((index):539)
underlined code:
.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';
Tried: Using CSS to affect div style inside iframe
(got errors with all examples "None worked").
I am running this function with onload="hello(this)" on my iframe.
Any other suggestions how I can edit that class to make its width 100%??
please try bellow code ... I hope you get result:
let myiFrame = document.getElementById("iframe-css").contentWindow;
let doc = myiFrame.document;
doc.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';
Adding a <style> element isn't the best way to do this. However, even if it was, you should try to avoid adding elements via innerHTML. It is better to use Document.createElement (document is an instance of Document) and Element.appendChild (all elements are instances of the Element class).
The best way to do this is by directly modifying the style of the elements in the class.
function hello() {
let myiFrame = document.getElementById("iframe-css");
let doc = myiFrame.contentDocument ?? myiFrame.contentWindow?.document ?? new Document();
let elements = doc.getElementsByClassName("2p3a");
for(let i = 0; i < elements.length; ++i) {
elements[i].style.width = "100%";
}
}
Also, the onload attribute sometimes doesn't work on an iFrame. You may have to use the DOM like this:
document.getElementById("iframe-css").onload = hello;
On a side note, you should generally stick to 2 or 4 spaces of indentation in JavaScript, but you chose 3.
Decided to use a different plugin since using the facebook iframe was causing some trouble. With this new plugin everything is working fine so yea.
Thanks to anyone who put effort to answering, I appreciate your help.

How do you make a bookmarklet change page icon?

Before I begin, this is NOT a duplicate. To explain my goal, I want a bookmark that, when clicked, changes the page icon WITHOUT loading a new tab. Other similar questions gave your bookmarklet an icon, but nothing accomplished what I wanted.
Here is the code I have right now:
data:text/html; charset=utf-8, <html><link rel="shortcut icon" href="http://link-to-my-icon.info/favicon.ico"></html>
It works, but it changes my tab. I want to keep the tab open, but edit the HTML to change the page icon. I've tried using
javascript: document.write(<link rel="shortcut icon" href="http://transparent-favicon.info/favicon.ico">);
as well, but it does absolutely nothing, while my first attempt at least changes the icon.
Any help would be greatly appreciated, thanks.
Checkout this gist and the demo.
//source: https://gist.github.com/mathiasbynens/428626
document.head || (document.head = document.getElementsByTagName('head')[0]);
function changeFavicon(src) {
var link = document.createElement('link'),
oldLink = document.getElementById('dynamic-favicon');
link.id = 'dynamic-favicon';
link.rel = 'shortcut icon';
link.href = src;
if (oldLink) {
document.head.removeChild(oldLink);
}
document.head.appendChild(link);
}

Microsoft Dynamics 365 Change Header Color on Form based on value

I have an option set on my Account / Sales form. Based on this value I want to change the header color at the top of the form.
I can do this manually through editing the CSS through the Developer Tools, however when I try and do this through Form Properties and Web Resources I cannot get the color to change.
As a base test I'm just trying to inject the CSS into the page through javascript.
Here is the CSS web resource that I created.
.ms-crm-Form-HeaderPosition {
background-color: rgba(2,206,239,1) !important;
}
Here is the javascript web resource I created:
function load_css_file(filename){
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
document.getElementsByTagName("head")[0].appendChild(fileref)
}
function myFormOnLoad(){
load_css_file('/WebResources/aws_ColoredHeaderMGA.css');
}
I then went to my Sales form, changed the form properties to load in my Javascript web resource and then told it to call the function myFormOnLoad as on OnLoad even for the form.
I'm not getting any errors, I know the javascript is getting called because I added an alert to it just to make sure and I did receive the alert.
What am I missing to get the header color to change?
In case someone is looking for working code, the below one we are using.
I guess the URL is the problem in OP. Add OrgName & remove extension (.css)
function LdCSS() {
var path = "/orgname/WebResources/new_custom";
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = path;
link.media = 'all';
head.appendChild(link);
}

How to refresh the page on document.write

I am using document.write in a function to give different CSS to user's based on their choosing.
function blue() {
document.write('<link rel="stylesheet" type="text/css" href="http://ilam.irib.ir/documents/697970/237563314/blue.css" />');
}
I am calling the function from an anchor tag.
function color2(){
document.getElementById("navigation").innerHTML +='<a class="myButton" onclick="blue()" background-color:"#05c8f2";></a>';
}
As you can guess, when the link is clicked, the page clears out and I get a blank page.
Is there any way to fix this problem? I don't want to stop page refreshing, I'm just trying to fix the problem in any way possible!
Note: don't ask why I'm adding code using JavaScript, and not directly into HTML code. This site is a large scale system and we just have access to JavaScript and CSS. So this is all we can do to edit our pages.
document.write rewrites the body , as a result the only thing in your document remains is the css file you added and hence it is blank.
View this
Code from above link :-
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.com/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
}
Instead of rewriting while dom , we append the link element inside head tag

Cannot set title and alt attributes in my img using javascript

I'm using the Google Image Search API, and largely copied this code, which builds the search results in my page.
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var linkContainer = document.createElement('div');
var title = document.createElement('div');
// We use titleNoFormatting so that no HTML tags are left in the title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
newImg.src = result.tbUrl;
newImg.className = 'googleSearchResult';
newImg.title = 'newTitle';
newImg.alt = 'newAlt';
var newLink = document.createElement('a');
newLink.href = "temp_url";
newLink.appendChild(newImg);
contentDiv.appendChild(newLink);
}
In the following lines,
newImg.src = result.tbUrl;
newImg.className = 'googleSearchResult';
newImg.title = 'newTitle';
newImg.alt = 'newAlt';
the first two, which set the image src and class, work fine, but the second two, which should set the title and alt of the image, don't work at all. Can anyone see why this would be happening? Thanks for reading.
EDIT:
Here is the HTML when inspected in Firefox through Firebug:
<img alt="" src="http://images.google.com/images?q=tbn:_HZix2CrLSLSOM::bestonlinetvseries.com/deadwood/deadwood_s01.jpg" class="googleSearchResult">
Here is the HTML when inspected in Google Chrome
<img alt src="http://images.google.com/images?q=tbn:_HZix2CrLSLSOM::bestonlinetvseries.com/deadwood/deadwood_s01.jpg" class="googleSearchResult">
EDIT:
What I am trying to do here is store an extra bit of data in the HTML for the image, to be used in a jQuery plugin later. If anyone can suggest an alternative way to do this, that would be great as well.
I suspect the problem lies elsewhere. Consider this example, which works fine in the browsers I've tested (Firefox, Chrome, IE):
var link = document.createElement("a");
link.href = "http://stackoverflow.com";
var img = document.createElement("img");
img.title="Hello";
img.alt="alt Hello";
img.src="http://jsfiddle.net/img/sprites.png";
link.appendChild(img);
document.body.appendChild(link);
alert(img.getAttribute("alt"));
alert(img.getAttribute("title"));
I would recommend checking to see if anything might be in front of the link/img element, as this would stop a tooltip from appearing on hover.
In response to your last edit: if you're just trying to store data associated with an image for later use you could use jQuery's data method.
Try:
img.setAttribute('title', 'someTitle');
Appearantly, there's a difference between 'properties' and 'attributes' in DOM scripting.

Categories