How to create Master pages using Javascript - javascript

I'm trying to create master pages using javascript. I created Javascript objects containing the html code then including the js the html files. The problem is that I cant inject css in the head of the html. the jquery append function is not working..

You don't really need to inject CSS in the head for it to style your page. I think you can just include the <link> tag anywhere in the DOM and it should work.
However, if you must include it in the head, try this:
function addcssfile(cssfile){
var head = document.head || document.getElementsByTagName('head')[0];
var s = document.createElement('link');
s.setAttribute('rel', 'stylesheet');
s.setAttribute('href', cssfile);
head.appendChild(s);
}
If you want to append just the CSS styles and properties, and not an actual CSS file, you can do this:
function addcss(css){
var head = document.head || document.getElementsByTagName('head')[0];
var s = document.createElement('style');
s.setAttribute('type', 'text/css');
if (s.styleSheet) { // IE
s.styleSheet.cssText = css;
} else { // the world
s.appendChild(document.createTextNode(css));
}
head.appendChild(s);
}

Related

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

Loading different JS file for iPad only?

I am trying to load a different Javascript file if the site is viewed on ipad.
I have the following code but it puts the code in head section (between head tags) because of this line of code:
var h = document.getElementsByTagName('head')[0];
I was just wondering how I can place the code where ever I want i.e. between a div without name or at the bottom of the page instead of placing automatically in between the head tags?
<script language="javascript">
if (navigator.userAgent.match(/iPad/i) != null){ // may need changing?
var js = document.createElement('script');
js.type = "text/javascript";
js.src = "mainaPPiPad.js";
var h = document.getElementsByTagName('head')[0];
h.appendChild(js);
}
</script>
Thanks in advance
You need to change this line to point at another element in the document:
var h = document.getElementsByTagName('head')[0];
To append it to the end of <body>, you'd do:
var h = document.getElementsByTagName('body')[0];
Or to append it to <div id="foobar">:
var h = document.getElementById('foobar');
Just select the element via JavaScript and append it. For example:
<div id="magic-div"></div>
document.getElementById('magic-div').appendChild(myNode);

Hide div from javascript

I have a script that brings up some things that I don't want (a selector).
The script brings up a div class named "selector", and I don't want that div class to show. (I have no access to the css files)
Here is the script:
<script language="javascript" type="text/javascript">
window.onload = function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.setAttribute("language", "javascript");
script.src = "http://js.sbrfeeds.com/js";
script.id = "widget-main-script";
document.body.appendChild(script);
}
Is there any way to put some code in the above script that will hide the div "selector" when loaded?
Basically, I want what's circled in the picture to not show, and it is in a div class name "selector".
Image here: http://imagizer.imageshack.us/v2/800x600q90/543/f385.png
document.getElementsByClassName('selector')[0].style.display = 'none';
Mind you, before you run that, you need to make sure your script fully loaded. Is there a reason you don't just add the script as a script tag so it will load when the page loads? Then you don't have to worry about all that mumbo jumbo.
Assuming that your Div has an ID (and you are using JQuery), you could do something like this: JSFiddle
$('#selDiv').removeClass('selector');
If you aren't using JQuery, you could do this: JSFiddle
document.getElementById("selDiv").className = "";
This isn't really a legitimate answer, but I ended up just hiding what I needed to be hid using a div class. Just throwing that here in case someone else needs it. You could also use a png file if it's an awkward shape to hide. Mine was just rectangular though.
var css = '.selector { display : none}',
header = document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
header.appendChild(style);
This will create a tag at header and then you can hide your element. Additionally you can set other CSS properties. Not sure this will work in your situation.

Unexpected call to method or property access - appendChild()

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.

How to add anything in <head> through jquery/javascript?

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.

Categories