Creating Style Node, adding innerHTML, add to DOM, and IE headaches - javascript

I have a two part question.
First, the scenario:
Due to some bizarre issues we've run into in regards to mobile browser support for NOSCRIPT, I'm tasked with coming up with an alternative solution to 'detect' JS. The solution logic is to have two DIVs on the page. One is an error stating you do not have JS and his shown by default. If one has JS, we then want to add a new STYLE block to the HEAD that over-rides the previous CSS and hides the error and instead shows the content.
The sample HTML:
<div id="div1">div 1 (should be shown if JS enabled)</div>
<div id="div2">div 2 (should be hidden if JS enabled)</div>
This is the JS I started with:
var styleNode = document.createElement('style');
styleNode.setAttribute("type", "text/css");
styleNode.innerHTML = "#div1 {display: block;} #div2 {display: none;}";
headTag.appendChild(styleNode);
But, I was having problems. Some googling resulting in this description of a security issue that IE can have if you try to insert innerHTML into a created element before placing it in the DOM:
http://karma.nucleuscms.org/item/101
So, I modified the script as such:
var styleNode = document.createElement('style');
styleNode.setAttribute("type", "text/css");
var headTag = document.getElementsByTagName("head")[0];
headTag.appendChild(styleNode);
var aStyleTags = headTag.getElementsByTagName("style");
var justAddedStyleTag = aStyleTags[aStyleTags.length-1];
justAddedStyleTag.innerHTML = "#div1 {display: block;} #div2 {display: none;}";
question 1: is that a valid workaround for the IE issue? Is there a more efficient solution?
question 2: even with the adjustment, the script still does not work in IE. It works fine in Firefox, but in IE 7 I get an "unknown runtime error".
I have a sample of this code up on JSBIN:
http://jsbin.com/ucesi4/4
Anyone know what's going on with IE?
UPDATE:
I stumbled upon this link via google. Note the last comment:
http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
That said, you really should put all
style rules in the HEAD for strict
compliance with XHTML. Doing this can
also be a little tricky because you
cannot use innerHTML to inject into
the HEAD or STYLE element directly.
(Both of these tags are READ ONLY.)
Eep! True? Is FireFox just being overly forgiving? Or is this just a very odd IE quirk?
UPDATE 2:
A bit more background on what we're trying to solve here. We're dealing with mobile devices and some of the antiquated devices a) don't support NOSCRIPT and b) have slow JS engines.
Since they don't support NOSCRIPT, we are by default showing an error, then hiding it via JS if they have it, and presenting them with the proper content. Because of the slow JS engines on these, people see the 'flicker' of the DIV's showing/hiding. This was the proposed solution to handle that, as it would load the CSS before the DIVs were even rendered.
Since it appears to be invalid, the solution will be that on these old devices, we'll use this method (as it seems to work, even if not in IE) and then all other proper browsers will do as suggested...we'll just update the DISPLAY CSS property via inline JS after each DIV is loaded in the DOM.
All that said, I'm still curious as to whether this issue is an IE bug, or if IE is actually adhering to the proper standards by making STYLE a read-only element.

In IE you can use style.styleSheet.cssText:
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) { // IE
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
Try this here: http://jsfiddle.net/QqF77/
See the answer on this question: How to create a <style> tag with Javascript

Don't use innerHTML, use document.createTextNode() and your life will become infinitely better ;)
var styleNode = document.createElement('style');
styleNode.setAttribute("type", "text/css");
var textNode = document.createTextNode("#div1 {display: block;} #div2 {display: none;}");
styleNode.appendChild(textNode);
headTag.appendChild(styleNode);
EDIT:
Since this solution doesn't seem to work for you, I'd abandon it. Instead go for a solution where styles are already defined and where you just disabled/enable styles via javascript if available.
You can do it this way:
<head>
<style>
.jsenabled #div2, #div1 { display: none;}
.jsenabled #div1, #div2 { display: block;}
</style>
<script>
//i know you don't use jQuery, but the solution should still be valid as a concept
//bind to DOM-ready, then set the class jsenabled on the body tag
$(function() {
$(document.body).addClass('jsenabled');
});
</script>
</head>
<body>
<div id="div1">div 1 (should be shown if JS enabled)</div>
<div id="div2">div 2 (should be hidden if JS enabled)</div>
</body>
EDIT 2:
If it has to be done prior to DOM ready, you could do something kinda ugly like this:
<head>
<style>
#div2, .show { display: block;}
#div1, .hide { display: none;}
</style>
</head>
<body>
<div class="hide">
<script>document.write('</div><div id="div1">');</script>
div 1 (should be shown if JS enabled)
</div>
<script>document.write('<div class="hide">');</script>
<div id="div2">div 2 (should be hidden if JS enabled)</div>
<script>document.write('</div>');</script>
</body>
Or to keep things simple, you could just do
<head>
<script>document.write('<style>#div1 {display: block;} #div2 {display: none;}</style>');
</head>
<body>
<div id="div1">div 1 (should be shown if JS enabled)</div>
<div id="div2">div 2 (should be hidden if JS enabled)</div>
</body>

Best practice is to put all the <link for CSS into the <head, and most <script at tne very end of the <body (except short fragments of <script that should execute ASAP should go in the <head). Both the standard and browsers allow you to do silly things, but just because it's acceptable doesn't mean it's a good idea.
Rather than go through all the rigamarole of creating a Style node and of manipulating the DOM (which just provide more opportunities for something to go wrong), I recommend a much simpler solution. Hard code as much as you can into your document (and style sheet?) in advance once (rather than creating things on the fly every time). Here's a rough example:
<body ...
...
<div id="warning" style="display: block;">
JS is required for this site, but isn't available ...
</div>
<div id="message" style="display: none;">
JS is available
</div>
...
<script ...
var warningEl = document.getElementById('warning');
warningEl.style.display = 'none';
var messageEl = document.getElementById('message');
messageEl.style.display = 'block';
</script ...
This should work reasonably well most of the time (it will certainly work in more browsers than what you tried to do initially). However, any attempt to change the DOM in any way before the page is initially displayed to the user is not guaranteed to work (in other words neither your way nor the example above will always work in all cases). The earlier you run your Javascript, the more likely DOM operations (including getElementById) may fail. And the later you run your Javascript, the more likely the user will notice a perceptible "flicker" of their display. So you're presented with a tradeoff choice between wide compatibility and noticeable flicker.
You can wait until the DOM is guaranteed to be fully ready before you run your Javascript ("ready" in jQuery, or addEventListener 'domcontextloaded', or even addEventListener 'load'). This is guaranteed to function correctly in all cases. But it will flicker (perhaps quite badly) in many cases.
The only way I know (but I hope somebody else knows more:-) to avoid entirely the possibility of flicker is to put in the <head a fragment of Javascript that changes window.location but does nothing else. (No references to the DOM, which are usually made obvious by the word "document" somewhere in the code.) The net effect if JS is available will be an immediate reload of a different page before much of anything is shown to the user. The initial page can contain your warning, and the new page the real stuff with no warning.
Even this method has some disadvantages though: First, the double download takes extra bandwidth and delays user visibility a little. This won't matter on typical desktops. But on handhelds it may not be acceptable. And second, it will raise havoc with SEO. The second page -that's supposed to be invisible and only accessed from the first page- may show up independently in webdexes so users can easily access it directly (you may be able to "fix" this with clever use of "canonical" and/or "meta...robots"). And the SERP of the initial page may fall precipitously when its only content is the warning message.

Related

Javascript library to gracefully downgrade custom elements in HTML at runtime

I would like to say
<html>
<body>
<mytag foo="bar">blah</mytag>
</body>
</html>
And define somewhere else how a <mytag> should behave. But for older browsers that do not play nicely with custom tags, I would like to just load a js library in the browser and have it automatically rewrite the above code as say
<html>
<body>
<div data-mytag data-foo="bar">blah</div>
</body>
</html>
Obviously this functionality could be hacked together in an hour, but I would prefer to use a tiny library that someone has written, for the sake of convention and possibly handy features. Do you know of one? Note: please don't reply about why I shouldn't use custom tags.
For the first part, maybe something like
<mytag>yo</mytag>
<script>
var map = {
MYTAG: function(s){
// surround content with stars
return '**'+s+'**';
}
}
Array.prototype.slice.call(document.getElementsByTagName('*')).forEach(function(tag){
// note on some IE versions you cant set innerHTML directly
if(map[tag.tagName]) tag.innerHTML = map[tag.tagName](tag.innerHTML);
})
</script>
For changing element tags at runtime, I can't recall if that's possible. People may cringe, but I'd maybe take the entire document.body.innerHTML replace it using regexes and reset it. If I knew I was the only creator of the HTML content that may take care of it..

Preloading a background-image with a temporary gif image

I have a couple of divs with background images. I would like to know how I can preload those background-images with a gif image since some of the background images are quite large. Doing the following does not work:
HTML:
<div id="glykopeels" onload="loadImage()">Glykopeels Content</div>
<div id="facials" onload="loadImage2()">Facials Content</div>
CSS:
#glykopeels{
background: #ebebeb url(http://lamininbeauty.co.za/images/products/preloader.gif) no-repeat top right;
background-size: contain;
}
#facials{
background: #ebebeb url(http://lamininbeauty.co.za/images/products/preloader.gif) no-repeat top right;
background-size: contain;
}
JS:
function loadImage(){
document.getElementById('glykopeels').style.background = '#ebebeb url(http://lamininbeauty.co.za/images/products/glykopeel.jpg);';
}
function loadImage2(){
document.getElementById('facials').style.background = '#ebebeb url(http://lamininbeauty.co.za/images/products/facial.jpg);';
}
I guess defining a different ID for that element in the onload function and defining css for that new ID is another possibility? Thus changing only the id of that element inside the onload function?
Thank you
First: there is no onload attribute for div's. EDIT: please read comments below, very interesting!
Secondly, you should place the url between quotes (escaping them if needed): url('http://lamininbeauty.co.za/images/products/facial.jpg')
Third, there was no image called preloader.gif, yet there was a image called loader.gif, so I used that one to 'fix' your css part for my solution in the jsfiddle demo link at the bottom.
During SO's server-move, I wrote a simple custom function for you that does exactly what you want.
Tested in IE6 and FF12.
To test this: please clear your browsers buffer, otherwise you can't SEE it in action (it would go too fast), since the images will probably be buffered on second view (again, perfect for your goal)!
JavaScript:
var repBg=function(a, t){ t=t||'*'; // by GitaarLAB
var c=document.getElementsByTagName(t), i=c.length, r=[];
while(i--){if (c[i].getAttribute(a)){r.push(c[i]);}} c=r; i=c.length;
repBg.exec=function(){
c[this['data-i']].style.background="#ebebeb url('"+this.src+"') no-repeat top right";
};
while(i--){ if (c[i].getAttribute(a)) {
r=new Image();
r.onload=repBg.exec;
r['data-i']=i;
r.src=c[i].getAttribute(a);
}}
};
// one could run repBg onload, but better to run it when the image has actually loaded, see html!
// window.onload=function(){ repBg('data-bg_img','div'); };
In your BODY: Add the attribute 'data-bg_img' (as per html5 convention, start with data-) to the elements you want to use this technique on and have it contain your background url, like this:
<div id="glykopeels" data-bg_img="http://lamininbeauty.co.za/images/products/glykopeel.jpg">Glykopeels Content</div>
The 'optional' initialization in your BODY:
<!--
trigger the replace background function when the loader image has actually loaded!
rewriting the onload with nothing to prevent infinite loop in IE6 (and greater?) !!
-->
<img src="http://lamininbeauty.co.za/images/products/loader.gif" style="display:none;" onload="this.onload=null; repBg('data-bg_img','div');">
Manual/explanation:
Images DO have a onload-event, so we place a loading-image in the html (at the bottom), that will trigger it's own onload-event, calling repBg() as soon as the browser has actually downloaded this loading-image!!!
The function repBg() takes up to 2 arguments:
the first mandatory string that contains the attribute that should be selected,
the second optional argument can define tagname (to limit the first argument).
When invoked, function repBg() will then search the body for elementTagNames that adhere to the second argument or * and then filter them with the first argument.
For each htmlObject that remains in the filtered htmlObjectCollection, a new image is created (not appended to the body) with the htmlObject's attribute-value (url) corresponding to the function's first argument as image-source, together with the htmlObjectCollection's referring id (attribute data-id) for reference.
As soon as these images load, they fire their onload event: calling repBg's exec method that replaces the background of the referenced htmlObject with the new freshly loaded (big) background-image (and the rest of your css). For further modularity you could expand on that function.
Lastly, note: the background images load in order they appear in source, aka the way you expect things to work!!
You can see it in action in this fiddle: http://jsfiddle.net/epdDa/
UPDATE VERSION 2: GRACEFUL FALLBACK!! AND COPY-PASTE NOBRAIN SOLUTION
It annoyed the living daylights out of me that my first solution did not provide graceful fallback. So I made a different solution that provides graceful fallback.
Also fully tested in IE6 and FF12
It works like this:
In your BODY: SIMPLY set your div's class to 'preload' and set it's style-attribute to the backgroundimage it should normally load. Like this:
<div id="facials" class="preload" style="background: #ebebeb url('http://lamininbeauty.co.za/images/products/facial.jpg') no-repeat top right;">Facials Content</div>
That was easy right?
Then place the following script in the HEAD (this is important) of the HTML:
// getElementsByClass original by dustin diaz, modified by GitaarLAB
document.getElementsByClassName=document.getElementsByClassName||function(searchClass,node,tag) {
var classElements = [], i=0, j=0;
if (!node){node = document;}
if (!tag){tag = '*';}
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
for (; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i]; j++;}
} return classElements;
};
var repBg=(function(n,u,p,a,i,r){ // by GitaarLAB
window.onload=function(){repBg(1);};
i=new Image(); i.onload=function(){this.onload=null; repBg(2);};
document.write("<style>."+n+"{background:"+p+" url("+u+") "+a+
" !important; background-size: contain !important;}"+
"</style>");
i.src=u; r=0;
return function(t){
r=r+t; if(r>2){
var c=document.getElementsByClassName(n), i=0, l=c.length, s;
repBg.exec=function(){
document.getElementById(this['data-id']).className='';
};
for(;i<l;i++){
r=new Image();
r.onload=repBg.exec;
r['data-id']=c[i].getAttribute('id');
s=c[i].getAttribute('style');
try { // sane browsers
r.src=s.match(/url\('?([^'"]*)'?\)/i)[1];
} catch(e) { // <IE8
r.src=s.cssText.match(/url\('?([^'"]*)'?\)/i)[1];
}
}
}
};
})('preload','http://lamininbeauty.co.za/images/products/loader.gif','#ebebeb','no-repeat top right');
Explanation:
It took me all night.. but I found a way.
If javascript is enabled, function repBg will start by writing an extra style-block to the documents head (where it is located, note to place it after your last css script), that sets the loader-background-image for all elements with the class 'preload' (thus displaying the load-image at pageload).
If a load-test image for the loading-image is loaded AND the window is loaded (to get to all the elements in the body), then it does basically the same as version 1. Only this time we fetch and match the url from the element's style-atribute and onload subsequently empty the element's style-attribute.
Since this function auto-executes and overwrites itself with a version similar to version 1 (as above), you can simply adjust parameters at the last line of function 'repBg'.
Note that: in it's initial sate repBg accepts a maximum of 4 arguments: className, Url, cssPrepend and cssAppend.
To see it in action (don't forget to clean your browsers buffer as explained),
click this fiddle: http://jsfiddle.net/epdDa/1/
Whoever uses this function, I would greatly appreciate it if you credit me!
UPDATE:
Extra explanations and answers to comments.
Main differences between the 2 versions
Technically both versions use almost the same techniques so there is no real difference there.
With version 1 the javascript is the glue that IS NEEDED to make the page work, but works in valid true xhtml and plain html.
However, people with javascript turned off will get a nonfunctional site (with only loading-gifs displayed). Note that all other current answers, including the direction you where going, suffer from this problem!
With version 2 the javascript is only the spice that enhances the page-interaction (the way websites should be coded), but only works in html (or invalid xhtml).
However this should make sure that people with javascript turned off still see a normal functioning page. IE: javascript is NOT NEEDED to display the site correctly. This concept is called 'graceful fallback' or 'degrading gracefully'. My vote no 1 for version 2.
Extra bonus: this path gives you plain vanilla validating and SEMANTIC html since you use ancient trusty in-line style, id and class. My vote no 2 for version 2
Why did I choose to use in-line css? Why 'must' you use in-line css for this to work?
First of all, I spent hours to avoid in-line css. (I did not loose them, I learned way's that did not work, just as useful). Next, I want to point out that again all current answers including the direction you were going, had the actual background image url separated from the css, while in the css you were setting the loader image on each div separately, something where a class would have made more sense. Version 2 simply uses a configurable classname.
Both reading and writing css blocks in the document's HEAD is kind of a mess..
And did I mention linked external css files..??
In my opinion, all this would need so much extra code and cpu-cycles AND blocking/halting the browser on every pageload, in order for the core-priciple to work: the last valid css-rule applies. So the loading image is displayed as soon as possible since it is the specified background image at pageload, exactly what one would want from such a feature. And if the element is no longer part of the 'preload' class? Right: it's inline css takes effect, updated as fast as the browsr can render (if the image is already loaded). Nice.
So if you sacrifice (true) xhtml-support by simply using document.write, it currently still turns out this way is the 'best' way to go (as you can read in the previous 2 links). AND it would still work with an external linked css. My third (KISS-)vote for version 2.
My fourth vote for version 2 is because: the repBg function is prepared to have it's exec method(=function) 'upgraded' so you can only take out the 'preload' value from the class' valuelist. A simple replace() would suffice (currently left out for speed).
My fifth and final vote for version 2 is that because of it's graceful fallback setup, it is also relatively easy to fix for or block some browsers to use the extra 'spice'.
Finally, as for speed: I think version 2 will always feel snappier: onload-image is displayed almost as fast as the browser can fetch it (as if this extra css was always there to begin with), the loading-animations load snappy since: their load is already initiated in the head, and the browser will not download the overruled images until called for by the function. Plus they look interactive without distraction. But.. when the actual background images are loaded and the css updates: bam! the image is there, without the top-to-bottom-scanning'-effect'. That effect feels damn snappy to. Actually I'm convinced and will be doing an adaptation for images in the galary, for the snap-feel and increased perceived initial pageload.. Note, this is my opinion. Your mileage may vary haha.
Good luck!!
(and please vote if you like/use this idea/function, thank you!!)
1) div elements doens't have a load event, this event is only for body, images and script tags.
EDIT: Like pointed by #icktoofay, in the HTML spec the onload exists for all elements, however this is not supported by the major browsers (yet).
2) place this script tag at the end of your html page:
<script>
function loadImages() {
var glykopeels = document.getElementById('glykopeels');
var facials = document.getElementById('facials');
glykopeels.style.backgroundImage = 'url(http://lamininbeauty.co.za/images/products/glykopeel.jpg)';
facials.style.backgroundImage = 'url(http://lamininbeauty.co.za/images/products/facial.jpg)';
​
3) You can set style.background like you did, but do not put the ; at the end of the string, otherwise it will not work.
fiddle: http://jsfiddle.net/pjyH9/
EDIT
Seems like the loader image does not show because once the browser receive the first bytes of the new image it removes the loader.gif from the background. Let's take another approach.
Here is a function that will load the image to cache and then - when image is loaded - set the image to the background of the element with the specified id.
function loadImageToBackground(elementId, imageUri) {
var img = new Image();
img.onload = function() {
document.getElementById(elementId).style.backgroundImage = "url('" + imageUri + "')";
};
img.src = imageUri;
}
The on the elements that you want the loader:
// past the element id and the image url to the function
loadImageToBackground('glykopeels', ​'http://image....');
I'm pretty sure that this will work. The function loadImageToBackground do the basic work, you can extend and add more functionalies if you want.
Here is fiddle with a working example: http://jsfiddle.net/pjyH9/19/
(It loads 2 images with 1.5mb each, so you can see the loader in action).
I think what you're trying to do is get the background image to switch out to the big JPG image after it's loaded. You should be able to adapt something like this to work for you:
<html>
<head>
<title>Image Load Test</title>
<script type="text/javascript">
function loadImage(preloader, imageDiv) {
document.getElementById(imageDiv).style.background = '#ebebeb url('+preloader.src+') no-repeat top right';
// I think resetting the background property also resets backgroundSize.
// If you still want it 'contained' then you need to set the property again.
document.getElementById(imageDiv).style.backgroundSize = 'contain';
}
</script>
<style type="text/css">
#testImage {
background: #ebebeb url(small-image.gif) no-repeat top right;
background-size: contain;
}
#preloads { display: none; }
</style>
</head>
<body>
<div id="testImage">Some Content</div>
<div id="preloads">
<img src="full-image.jpg" onload="loadImage(this, 'testImage')">
</div>
</body>
</html>
The main difference here is that I'm preloading the JPG image in an <img> that's hidden in a <div> with the display: none property to keep it hidden. I'm not sure exactly what the onLoad event does for divs, but I'm pretty sure it's not what you're wanting. Putting an onLoad event in an img element causes the event to fire once the image has fully loaded, which I believe is what you want.
EDIT: I added a line in the JavaScript to reset the background-size property. If that's not what you wanted then just ignore that part.

Create new (not change) stylesheets using jQuery

We've got a little tool that I built where you can edit a jQuery template in one field and JSON data in another and then hit a button to see the results immediately within the browser.
I really need to expand this though so the designer can edit a full CSS stylesheet within another field and when we render the template, it will have the CSS applied to it. The idea being that once we've got good results we can take the contents of these three fields, put them in files and use them in our project.
I found the jQuery.cssRule plugin but it looks like it's basically abandoned (all the links go nowhere and there's been no development in three years). Is there something better or is it the only game in town?
Note: We're looking for something where someone types traditional CSS stylesheet data in here and that is used immediately for rendering within the page and that can be edited and changed at will with the old rules going away and new ones used in their stead. I'm not looking for something where the designer has to learn jQuery syntax and enter in individual .css("attribute", "value") type calls to jQuery.
Sure, just append a style tag to the head:
$("head").append("<style>p { color: blue; }</style>");
See it in action here.
You can replace the text in a dynamically added style tag using something like this:
$("head").append("<style id='dynamicStylesheet'></style>");
$("#dynamicStylesheet").text(newStyleTextGoesHere);
See this in action here.
The cleanest way to achieve this is by sandboxing your user-generated content into an <iframe>. This way, changes to the CSS won't affect the editor. (For example, input { display:none; } can't break your page.)
Just render out your HTML (including the CSS in the document's <head>, and write it into the <iframe>.
Example:
<iframe id="preview" src="about:blank">
var i = $('#preview')[0];
var doc = i.contentWindow || i.contentDocument;
if (doc.document) doc = doc.document;
doc.open('text/html',true);
doc.write('<!DOCTYPE html><html>...</html>');
doc.close();
If the user should be able to edit a whole stylesheet, not only single style attributes, then you can store the entered stylesheet in a temporary file and load it into your html document using
$('head').append('<link rel="stylesheet" href="temp.css" type="text/css" />');
sounds like you want to write an interpreter for the css? if it is entered by hand in text, then using it later would be as simple as copy and pasting it into a css file.
so if you have a textarea on your page to type in css and want to apply those rules when you press the button, you could use something like this (only pseudocode, needs work):
//for each css id in the text area
$.each($('textarea[name=cssTextArea]').html().split('#'), function({
//now get each property
$.each($(this).split(';'), function(){
$(elem).css({property:value});
});
});
then you could write something to go through each element that your designer typed in, and get the current css rules for it (including those that you applied using some code like the snippet above) and create a css string from that which could then be output or saved in a db. It's a pain and much faffing around with substrings but unfortunately I don't know of a faster or more efficient way.
Hope this atleast gives you some ideas

Cufon syntax for multiple elements/selectors?

I'm using Cufon to replace the font used for multiple elements. The syntax I have is this:
<script type="text/javascript">
Cufon.replace('h1.elementClassName, h2.newElementClassName, div#confirmationElementClassNameAndMore, h5.otherClassBlaBlaBla');
</script>
Apparently, it needs to be all on 1 line, otherwise it just doesn't work. But it becomes difficult to read as I add more elements to the list.
I've also seen the syntax below somewhere, but I was not sure, if declaring the REPLACE multiple times would slow down the loading:
<script type="text/javascript">
Cufon.replace('h1.elementClassName');
Cufon.replace('h2.newElementClassName');
Cufon.replace('div#confirmationElementClassNameAndMore');
Cufon.replace('h5.otherClassBlaBlaBla');
</script>
Will it affect speed or is it safe to use.?
Or is there another syntax that helps with visibility.?
There is no need to use cufon now, most of the browsers are able to render custom fonts using CSS only. Take a look here http://www.fontsquirrel.com/fontface/generator. Fontsquirrel can convert you font for all browsers and will generate CSS for you.
Font-face is inconsistent across browsers - you have to tweak margins to get a consistent result. Some fonts, when in small size, may also render really wrong.
This is the syntax to select more than one element with Cufon:
<script type="text/javascript">
Cufon.replace('h1, h2, h3', {fontFamily: 'FontName'});
</script>

Style display not working in Firefox, Opera, Safari - (IE7 is OK)

I have an absolutely positioned div that I want to show when the user clicks a link. The onclick of the link calls a js function that sets the display of the div to block (also tried: "", inline, table-cell, inline-table, etc). This works great in IE7, not at all in every other browser I've tried (FF2, FF3, Opera 9.5, Safari).
I've tried adding alerts before and after the call, and they show that the display has changed from none to block but the div does not display.
I can get the div to display in FF3 if I change the display value using Firebug's HTML inspector (but not by running javascript through Firebug's console) - so I know it's not just showing up off-screen, etc.
I've tried everything I can think of, including:
Using a different doctype (XHTML 1, HTML 4, etc)
Using visibility visible/hidden instead of display block/none
Using inline javascript instead of a function call
Testing from different machines
Any ideas about what could cause this?
Since setting the properties with javascript never seemed to work, but setting using Firebug's inspect did, I started to suspect that the javascript ID selector was broken - maybe there were multiple items in the DOM with the same ID? The source didn't show that there were, but looping through all divs using javascript I found that that was the case. Here's the function I ended up using to show the popup:
function openPopup(popupID)
{
var divs = getObjectsByTagAndClass('div','popupDiv');
if (divs != undefined && divs != null)
{
for (var i = 0; i < divs.length; i++)
{
if (divs[i].id == popupID)
divs[i].style.display = 'block';
}
}
}
(utility function getObjectsByTagAndClass not listed)
Ideally I'll find out why the same item is being inserted multiple times, but I don't have control over the rendering platform, just its inputs.
So when debugging issues like this, remember to check for duplicate IDs in the DOM, which can break getElementById.
To everyone who answered, thanks for your help!
Can you provide some markup that reproduce the error?
Your situation must have something to do with your code since I can get this to work on IE, FF3 and Opera 9.5:
function show() {
var d = document.getElementById('testdiv');
d.style.display = 'block';
}
#testdiv {
position: absolute;
height: 20px;
width: 20px;
display: none;
background-color: red;
}
<div id="testdiv"></div>
Click me
Found the answer :
I need to use the following to make it work on both browsers :
document.getElementById('editRow').style.display = '';
Actually I was experiencing the same problem you're describing here. What actually fixed my issue was changing the document properties.
Old DOCTYPE/html spec
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
Replaced with
<html>
Check the error console (Tools Menu > Error Console in Firefox 3) to make sure that there isn't another error happening that you're not seeing, which is stopping your script from working.
Try setting the height and width of the div, and make sure it is on top by setting its z-index higher than everything else. If the absolutely positioned div is inside an element that is relatively positioned, it's top and left location is based off the top and left of the relatively positioned element. Try putting your div just under the body element.
You must write a window.onload method:
window.onload = document.getElementById('testdiv').style.display='inline';
Or you can also make a variable:
var d = document.getElementById('testdiv');
window.onload = d.style.display = 'inline';
There is an annoying display error on Firefox 3.5 but not on IE7 or Firefox 2.0.9
I have 3 DIV's position absolute - the first with plain text; the second with a CSS menu (sucklefish type with UL and LI) and the third ditto. The third will not display at all even though the coding has been checked and found to be perfect with W3C's HTML validator.
As a temporary measure, I have merged the second and third DIV's contents.
Things must be bad at Mozilla when IE7 and FF2 display OK but not FF 3.5
I'll give you a BIG hint:
<div style="..." class="..."> ... </div>
If you have something in style, then document.style will work!
If you have something in class, it will not show up in document.style and class="..." will OVERRIDE it!
Think about this and this will clear up SO MANY ISSUES. Just this one little understanding will RID you of this MIND VIRUS. Have a good day. Cheers, Ron Lentjes, LC CLS.

Categories