I'm making a zoom button to add and remove a CSS file and for some reason I can't seem to add it in IE 8
First I tried this
document.createStyleSheet('style/zoom.css');
given that the jquery solution
$("head").append($("<link my style sheet />"));
seems to only work in FF and IE9 via my testing
I checked around the overflow and found this solution
$('#zoomlink').replaceWith($('<link>', {
id: 'zoomlink',
href: 'style/zoom.css',
type: 'text/css',
rel: 'stylesheet'
}));
But still no love to be found so then frustrated i found this
var $link = $('<link>');
$('head').add($link);
$link.attr({
type: 'text/css',
href: 'style/zoom.css',
type: 'text/css',
rel: 'stylesheet',
media: 'screen'
});
which im not certain would ever work but then finally i decided it way time to simply post a question.
I'm still not certain on how to remove the style sheet later via javascript but I need to first determine how to add a new style sheet in IE 8.
Maybe this will help (Sorry, can't try it in IE8):
(function() {
var s = document.createElement('link');
s.type = 'text/css';
s.rel = 'stylesheet';
s.href = 'http://yourdomain.com/style.css';
document.getElementsByTagName("head")[0].appendChild(s);
})();
To remove it I would assume a simple remove() would work
$("#zoomlink").remove();
To add a new link using jQuery with this syntax:
$("head").append(unescape("%3Clink id='zoomlink' rel='stylesheet' type='text/css' href='style/zoom.css'%3E%3C/link%3E"));
or using pure JavaScript
var e = document.createElement('link');
e.id = 'zoomlink'
e.rel = 'stylesheet';
e.type='text/css';
r.href='style/zoom.css'
document.getElementsByTagName("head")[0].appendChild(e);
There is many other way of writing the same but the idea is the same, remove the old reference element and add a new one.
Related
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
I have created a bookmarklet that executes the below code, adding css styling to the page. It works on all tried sites in Chrome and Firefox, but fails for some sites on IE. It's always the same sites that fail.
The fourth line fails with "Unexpected call to method or property access" for SOME sites, only on IE.
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(""));
head.appendChild(style);
Two sites that fail on IE 10:
http://www.momswhothink.com/cake-recipes/banana-cake-recipe.html
http://www.bakerella.com/
I think your problem is this line:
style.appendChild(document.createTextNode(""));
Here you are inserting a Text Node into a Style element, which according to the HTML specification is not allowed, unless you specify a scoped attribute on the style.
Check the specification of style here (Text Node is flow content).
You can find good ways to create the style element in a crossbrowser way here.
probably because you forgot to add document.ready()
Using jquery
$(document).ready(function(){
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(""));
head.appendChild(style);
});
Using javascript
Try wrapping your javascript in an onload function. So first add:
<body onload="load()">
function load() {
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(""));
head.appendChild(style);
}
I'm not sure why you're getting that error in IE10... I know in IE<9 an error is thrown if you try to modify the innerHTML of a <style> tag. It's still doable, you just have to do a bit of a workaround. For example (using jQuery):
var customCSS = "body { color: red; }";
var customStyle = $('<style type="text/css" />');
try {
$(customStyle).html(customCSS); // Good browsers
} catch(error) {
$(customStyle)[0].styleSheet.cssText = customCSS; // IE < 9
}
$(customStyle).appendTo('head');
Hope this helps.
Do you really have to dynamically add the style section to the page? What about adding the attribute, itself, on the fly, like this:
$(document).ready( function() {
$('[id="yourObjID"]').css('yourAttribute','itsvalue');
});
Adding the style section dynamically, rather than the attribute, seems like way overkill, to me.
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.
Problem exists only on FireFox (from 3.6 up to current 9), other browsers are fine. My code looks like this:
jQuery.extend({
AnchorFromUrl : function(url) {
var anchor = url.substr(1).replace('.html','');
$.fizzer_anchor = anchor;
window.location.hash = anchor;
return anchor;
}
});
The most weird thing is that if I place an alert before the window.location.hash = anchor; line, after clicking Ok favicon doesn't disappear, remove that alert() and you get your favicon disappearing.
Note: it also drops the favicon if you just do window.location = something.
I had the same problem, but found this interesting post and it worked for me, its just adding 2 lines of javascript.
The problem occure when the hash element changes, so, we need to re-stablish it via javascript
http://kilianvalkhof.com/2010/javascript/the-case-of-the-disappearing-favicon/
this is the code
function setFavicon() {
var link = $('link[type="image/x-icon"]').remove().attr("href");
$('<link href="'+ link +'" rel="shortcut icon" type="image/x-icon" />').appendTo('head');
}
Or (thanks to Mottie) using jQuery detach
$('link[type*=icon]').detach().appendTo('head');
It worked for me :
var link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = 'FAV_ICON_URL';
document.getElementsByTagName('head')[0].appendChild(link);
Refer : Changing Website Icon Dynamically
I noticed this behaviour, too. Every now and then Firefox drops a favicon or it refuses to put the favicon alongside my bookmark. I think this is a Firefox bug.
To workaround this (and for other functionality), I installed the Favicon Picker add-on. Of course, this doesn't solve your problem on other computers, like clients and the like.
I'm working with a CMS, which prevents editing HTML source for <head> element.
For example I want to add the following above the <title> tag:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
You can select it and add to it as normal:
$('head').append('<link />');
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
const link = document.createElement('link');
link.href = 'href';
link.rel = 'rel';
document.getElementsByTagName('head')[0].appendChild(link);
jQuery
$('head').append( ... );
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
You can use innerHTML to just concat the extra field string;
document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'
However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.
I haven't looked at the API in years, but you could also use document.write, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.
In the latest browsers (IE9+) you can also use document.head:
Example:
var favicon = document.createElement('link');
favicon.id = 'myFavicon';
favicon.rel = 'shortcut icon';
favicon.href = 'http://www.test.com/my-favicon.ico';
document.head.appendChild(favicon);
Create a temporary element (e. g. DIV), assign your HTML code to its innerHTML property, and then append its child nodes to the HEAD element one by one. For example, like this:
var temp = document.createElement('div');
temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
+ '<script src="foobar.js"><\/script> ';
var head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
Compared with rewriting entire HEAD contents via its innerHTML, this wouldn’t affect existing child elements of the HEAD element in any way.
Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval().
Try a javascript pure:
Library JS:
appendHtml = function(element, html) {
var div = document.createElement('div');
div.innerHTML = html;
while (div.children.length > 0) {
element.appendChild(div.children[0]);
}
}
Type:
appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');
or jQuery:
$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));
With jquery you have other option:
$('head').html($('head').html() + '...');
anyway it is working. JavaScript option others said, thats correct too.