var cssId = '../../../css/export-csv.css';
if (!document.getElementById(cssId))
{
var div = document.getElementsByTagName('div')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.media = 'all';
div.appendChild(link);
}
I want to import a CSS file named 'export-csv.css' in my js file but I am not able to do that. Thanks in advance
href is used to reference the id and move the link from one place to another where its not assign. If you want to assign any value make it as "ID or class" then it will easy for you to call in javascript.
Try document.getElementsByTagName( "head" )[0].appendChild( link ); instead of
var div = document.getElementsByTagName('div')[0];
div.appendChild(link);
and check that css file path is correct , it should resolve the issue. More details at How to load up CSS files using Javascript?
function loadCSS(filename){
var file = document.createElement("link");
file.setAttribute("rel", "stylesheet");
file.setAttribute("type", "text/css");
file.setAttribute("href", filename);
document.head.appendChild(file);
}
//just call a function to load a new CSS:
loadCSS("path_to_css/file.css");
So the following code should do the trick:
var aCSS=document.createElement('link');
aCSS.setAttribute('rel', 'stylesheet');
aCSS.setAttribute('type', 'text/css');
aCSS.setAttribute('href', 'someCssName');
document.getElementsByTagName('head')[0].appendChild(aCSS);
You can also load it in a blocking way by using document.write. The issue with loading CSS dynamically is that it degrades the user experience a lot, as the user will see a flickering of things at best case, and two different stories of the same element at worst case (slow css loading). I am not sure what is the use case, but please be careful when loading CSS dynamically.
I would suggest you using gulp or grunt to combine your css into one minified file and this would be a better approach IMO.
A few pieces are wrong here.
Your cssId looks like a file path. It could conceivably be an id but I doubt it.
There is no href. Since you are using an external stylesheet (<link> tag), your code needs to give the stylesheet an href, otherwise the browser will have no idea where to go fetch the styles from.
Inserting a stylesheet into a div is strange. It is more appropriate to put them in the head. While HTML5 does allow you to be a rebel, there are far more downsides than upsides to breaking this rule.
Here is a fixed example:
var cssId = 'some-legitimate-id';
if (!document.getElementById(cssId))
{
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.media = 'all';
link.href = '../../../css/export-csv.css';
document.head.appendChild(link);
}
Try this:
var div = document.createElement("div");
In place of:
var div = document.getElementsByTagName('div')[0];
Might be unable to find the div[0].
Related
I am using the following script to apply the stylesheet only if the class .item-label is not present on the page. I does not seem to work. Any ideas where my script is wrong? It seems the script is ignoring the class: .badge-icon icon-template... It doesn't matter if it is present or isn't present. I have the script loading at the bottom of the page.
<script>
if(!document.querySelector('..badge-icon icon-template')){
var link_el = document.createElement('link');
link_el.rel = 'stylesheet';
link_el.href = 'https://sub.domain.com/tester1.css';
document.head.appendChild(link_el);
}
</script>
So,
it seems superfluous to remind you that there may be infinite reasons why your code, apparently correct, does not work.
Assuming that your page does not contain errors in the HTML, or in some script, there could be two potential causes:
Your script is executed before the document is loaded, or the css file is not downloaded as it is already in the browser cache or all things.
try adding this script and then if the problem persists could you add the browser console output to the question?
<script>
document.addEventListener("DOMContentLoaded", function(){
if(!document.querySelector('.badge-icon icon-template')){
var noCache = '?' + new Date().getTime(); // add timestamp to url to force file upload
var link_el = document.createElement('link');
link_el.rel = 'stylesheet';
link_el.href = 'https://sub.domain.com/tester1.css' + noCache;
document.head.appendChild(link_el);
}
});
</script>
Just Add type also:
var link_el = document.createElement('link');
link_el.rel = 'stylesheet';
link_el.type = 'text/css';
link_el.href = 'tester1.css';
document.head.appendChild(link_el);
Check it here
Just put your code just before the ending </body> tag this should ensure the document is loaded
<script>
// DOM available
</script>
</body>
Is it possible to import css stylesheets to test.php head after redirect page to test.php after click on a href link from index page using Javascript? If so, how can it be done?
problem is that styles.css not working or display in test.php page?
i have code like this:
Index Page
<a id="some_id" class="optional_has_click">Click Me</a>
Jquery
<script type="text/javascript">
$(document).ready(function(){
$("#some_id").click(function(){
// add dynamically css file from external link and display to head
window.location.href = 'test.php';
var cssId = 'styles';
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://example.com/styles.css';
link.media = 'all';
head.appendChild(link);
document.write("<style>#jstree-marker-line,
#preloader{ background:none !important}</style>");
});
});
</script>
test page
<div id="container">
<p>test</p>
</div>
You cannot use document.write after the page has loaded, but if you really want to add styles like this to the head of the page you could potentially try something like this:
$("head").append("<style>...</style>");
But, it's probably better to do something like this when you want to update a style on the page
$("#jstree-marker-line").css("background", "none");
Or you could have a class with the styles you need defined on the page and use jquery's addClass to add that class dynamically on click
Using window.location.href = 'test.php'; will load a different page and stop any JavaScript running after that point.
Check out this question: How can I make JavaScript make (produce) new page? as it may answer your problem, or run the rest of the script on the test page.
Also check out #JenGettings' answer instead of document.write as it will overwrite the page.
I'm new to javascript.
I'm trying to load a .css file using the following javascript code, but it seems not working.
var myCss = document.createElement("link");
myCss.type = "text/css";
myCss.rel = "stylesheet";
myCss.href = "mycss.css";
document.getElementsByTagName("head")[0].appendChild(myCss);
Can anyone help?
thanks.
You have in stackoverflow another question about it, you can find it here:
How to load up CSS files using Javascript?
Which is a "oldschool" way to do it, just like user58777 said. (Credits go to him)
His code:
var $ = document; // shortcut
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!$.getElementById(cssId))
{
var head = $.getElementsByTagName('head')[0];
var link = $.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);
}
Why are you trying to do this? What benefit are you expecting?
I've never come across a situation where this is a good idea. CSS files are usually pretty small, so you aren't really gaining much by loading them dynamically. Just do the load in the head tag.
Anyway, the code you have should work. Just be sure that path is correct (it will be relative to the html file you're running)
Another solution would be to load an html file with all of the markup you need, and append it to the body. Check out the jQuery.load function The line below will load gameMarkup.html into the body tag.
$( "body" ).load( "gameMarkup.html" );
You can include all of the markup for your game here (not just styles). Generating elements with js can be useful, but it makes the code harder to maintain.
If you aren't using jquery, you can do the same thing with XHR, but it will be a lot more lines of code.
I want to make an javascript file (attached to some website), which generates available stylesheets and while clicked on one's name changes the current stylesheet for the chosen one. I do it like that:
for(var i=0;i<document.getElementsByTagName("link").length;i++)
{
var style = document.getElementsByTagName("link").item(i).href //getting name
//and here is my problem - I'd like to change that HTML code to js code, so that it generates a link wchich should change the style. I can't figure it out how to change that to js.
STYLE 3
}
//Here is the function that changes stylesheet (not mine, but working)
function changeCSS(cssFile, cssLinkIndex)
{
var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);
var newlink = document.createElement("link")
newlink.setAttribute("rel", "stylesheet");
newlink.setAttribute("type", "text/css");
newlink.setAttribute("href", cssFile);
document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}
Can you please verify my code and help me with changing HTML code with link, to js code?
//Edit
I'm sorry but it's still not working... The website on wchich i'm using the code has 3 stylesheet, but i get no result.
for(var i=0;i<document.getElementsByTagName("link").length;i++)
{
var style = new String(document.getElementsByTagName("link").item(i).href));
var a = document.createElement("a"); //create an anchor
a.textContent = a.innerText = "Style "+i; // Set its text to Style+i
a.onclick = function(){ changeCSS(style,0)}; // When you click it, you call changeCSS
document.body.appendChild(a); // Append it to the body
}
I used your code, like above.
Inside your loop:
var a = document.createElement("a"); //create an anchor
a.textContent = a.innerText = "Style "+i; // Set its text to Style+i
// When you click it, you call changeCSS
a.onclick = function(){ changeCSS(style,0)};
document.body.appendChild(a); // Append it to the body
If you want to append it to another element, change
document.body.appendChild(a);
To
whatEverElement.appendChild(a);
Some remarks:
appendChild adds an element as a child of another element, just like in changeCSS
I set both textContent and innerText to support old IE, if you don't need to, change to the textContent alone.
This code is assumed to be in the for loop.
Depending on what style is, there might be a closure trap here, if you see a problem with all elements getting the same style, that's what you got, and you need to wrap the code in another IIFE.
Here is a working example
Note it doesn't use change CSS, but alert because I don't know how to load external sheets in JSFiddle.
I'm new to Javascript (but not HTML or CSS) and am trying to use this script by Lalit Patel to detect whether a font is installed on the user's system, and if not, to serve a modified style sheet. I've been successful in getting the first part to work: I uploaded the fontdetect.js file, called it in my header, then pasted this before the end of my body tag:
<script type="text/javascript">
window.onload = function() {
var detective = new Detector();
alert(detective.detect('Courier'));
};
</script>
(With Courier used as an example.) This causes an alert to pop up on page load telling me whether a font is installed, and works beautifully. But I don't know how to get the script to, instead of triggering an alert, grab a different stylesheet. This seems like basic stuff but I just can't find the specifics anywhere, even though I've been plowing through Javascript tutorials. Any guidance would be greatly appreciated!
If any more specifics are needed: If a user doesn't have the custom font installed or has custom fonts turned off entirely, I'd like to, using CSS change the size/spacing properties of the text so that the fallback font is able to fit in the same space.
var detective = new Detector();
if (!detective.detect('Courier')){
var s = document.createElement('link');
s.rel = 'stylesheet';
s.type = 'text/css';
s.media = 'all';
s.href = '/link/to/alternative/stylesheet.css';
document.getElementsByTagName('head')[0].appendChild(s);
}
Guessing something like that. if .detect() fails, it will dynamically create and insert a stylesheet in to the page. If you encounter problems, you can also use .setAttribute() off of the s element.
You can use JS to add a stylesheet to the website:
var detective = new Detector();
if (!detective.detect('Courier')){
document.createStyleSheet('location/stylesheet.css');
}
else
{
document.createStyleSheet('location/otherstylesheet.css');
}
So you could do a check to see if the Dectector returns true, if not load one style, if it does then load the other.
After trying all the methods presented, this is the one that worked for me (from this answer, but it's really a mix of the two answers presented here). It should be noted that this works in IE8, unlike most of the other methods (sadly I do need IE8 compatibility).
<script type="text/javascript">
window.onload = function() {
var detective = new Detector();
if (!detective.detect('Meat')){
var url = 'link/to/style.css'
if(document.createStyleSheet) {
try { document.createStyleSheet(url); } catch (e) { }
}
else {
var css;
css = document.createElement('link');
css.rel = 'stylesheet';
css.type = 'text/css';
css.media = "all";
css.href = url;
document.getElementsByTagName("head")[0].appendChild(css);
}
}
};
</script>
This detected that my browser wasn't accepting embedded fonts ("Meat" being one of the fonts I embedded) and served up the alternate CSS (although with a slight delay/flash of unstyled text, maybe because it's at the bottom of the page?) Anyhow, thanks again for all the help!