IE doesn't apply dynamically loaded CSS - javascript

It appears as though IE (older versions at least) does not apply CSS that is loaded dynamically. This can be a pain point if you load a page containing CSS via ajax into a "lightbox" or "colorbox".
For example, say your HTML page has a div named "taco":
<style>#taco {color:green;}</style>
<div id="taco">Hola Mundo!</div>
"Hola Mundo!" will be green since the CSS was included in the original HTML page. Then some Javascript happens and appends this to "taco":
<style>#taco {color:green;}</style>
<div id="taco">
Hola Mundo!
<style>#burrito {color:red;}</style>
<span id="burrito">mmmm burrito</span>
</div>
In all browsers except IE, burrito's font will be red.
So is there a way to do this in IE? It seems as though there is not.

The style tag is only allowed in the head section. Placing it somewhere else is simply invalid and that has nothing to do with IE.
More information.
By the way, to solve your problem if you canĀ“t put the styles in a global style-sheet, you can use the 'style' attribute to modify elements:
<p style="...">
Or you can use an iframe but then you'd have to serve a whole page instead of just a few tags.

You might want to start using jQuery's .CSS methed for dynamic style changes like that.
$("#jane").css('color', '#0F0');
Or just plain jane Javascript:
document.getElementById['sally'].style.color = '#0F0';
EDIT:
Have your ajax inject this:
<div id="jane">
<div id="sally">Hi, I'm Sally!</div>
<script>document.getElementById['sally'].style.color = '#0F0';</script>
</div>
Or Why not just inject elements with inline styles computed server side?:
<div id="jane">
<div id="sally" style="color:#0F0">Hi, I'm Sally!</div>
</div>

If there is no way to do this, and you don't want to change your server-side code, here is a way for very simple style elements:
// In the callback function, let's assume you're using jQuery
success: function( data ) {
// Create a dummy DOM element
var el = document.createElement( 'div' );
// Add the html received to this dummy element
el.innerHTML = data;
// so that you can select its html:
var s = $( 'style', el ).text();
// Delegate to another function, it's going to get messy otherwise
addRules( s );
}
function addRules( s ) {
// First, separate your strings for each line
var lines = s.split( '\n' ),
// Declare some temporary variables
id,
rule,
rules;
// Then, loop through each line to handle it
$.each( lines, function() {
id = $( this ).split( ' ' )[ 0 ];
// Get the rules inside the brackets, thanks #Esailija
rules = /\{\s*([^}]*?)\s*\}/.exec( $( this ) )[ 1 ];
// Split the rules
rules = rules.split( ';' );
$.each( rules, function() {
rule = $( this ).split( ':' );
// Apply each rule to the id
$( id ).css( $.trim( rule[ 0 ] ), $.trim( rule[ 1 ] ) );
} );
} );
}
So, yeah, basically I'm making a CSS parser.
This is a very basic parser however.
It will parse the following rules only:
#some-id { some: rule; another: rule; }
#other-id { some: rule; yet: another; rule: baby; }

If you load a linked stylesheet dynamically (via AJAX) into a webpage, IE < 8 does not even recognize the LINK tag.
If you load a SCRIPT tag dynamically IE < 8 will not parse it.
Jeron is correct, the only way to dynamically load HTML and have it styled is via iframe, but I am testing the idea of reflowing the container.

Related

TinyMCE update Toolbar (after init) when you have Editor on method

I'm working on a Google Fonts plugin for WordPress and I try to have the same effect as the core WYSIWYG editor. Basically when you click on element (inside the Editor) with font class I want to get the class and then based on that reload the font family/style listbox in the Toolbar.
(I found couple of hacks here on SO like this one Proper Way Of Modifying Toolbar After Init in TinyMCE but nothing that works like the WP core example)
There is the same functionality when you click on P, H1, H3, H3 ... How they do it? Can you point me at least to the JS file in WordPress distro; I think I can figure it out if see the code.
Here is GIF that demonstrates what I'm talking about. Thanks in advance.
I found the solution and because it's not a hack, like the other ones I found on SO, I will post it in here and hopes it will help anyone else that's trying to do something similar.
First to access the button/listbox need to use onpostrender with a callback function.
editor.addButton( 'developry_google_font_family_button', {
type : 'listbox',
onpostrender : fontFamilyNodeChange,
value : '',
...
Next the callback function should look something like this:
function fontFamilyNodeChange() {
var listbox = this;
editor.on('NodeChange', function( e ) {
// This next part is specific for my needs but I will post it as an example.
var selected = [];
if ( $( e.element ).hasClass( 'mce-ga' ) ) { // this a class I add to all elements that have google fonts format
// Then I strip the classes from classList that I don't need and add the rest into an array (e.g ['roboto', '100'])
var gfont_options = $( e.element ).attr('class')
.replace('mce-ga', '')
.replace('mce-family-', '')
.replace('mce-weight-', '')
.trim()
.split(' ');
selected.push( gfont_options );
// At end I add the new value to listbox select[0][0] (e.g. 'roboto')
listbox.value(selected[0][0]);
}
});
}
And here is an example:

I have an error in Javascript with an A href

I don't understand why this an issue.
Could someone explain the issue and may be a possible fix.
Thank you.
Error:
XHTML element "a" is not allowed as child of XHTML element "script" in this context
Code:
<script type="text/javascript">
// Andy Langton's show/hide/mini-accordion - updated 23/11/2009
// Latest version # http://andylangton.co.uk/jquery-show-hide
// this tells jquery to run the function below once the DOM is ready
$(document).ready(function() {
// choose text for the show/hide link - can contain HTML (e.g. an image)
var showText='More Info';
var hideText='Less Info';
// initialise the visibility check
var is_visible = false;
// append show/hide links to the element directly preceding the element with a class of "toggle"
***$('.toggle').prev().append(' ('+showText+')');***
// hide all of the elements with a class of 'toggle'
$('.toggle').hide();
// capture clicks on the toggle links
$('a.toggleLink').click(function() {
// switch visibility
is_visible = !is_visible;
// change the link depending on whether the element is shown or hidden
$(this).html( (!is_visible) ? showText : hideText);
// toggle the display - uncomment the next line for a basic "accordion" style
//$('.toggle').hide();$('a.toggleLink').html(showText);
$(this).parent().next('.toggle').toggle('slow');
// return false so any link destination is not followed
return false;
});
});
<script>
There are differences between HTML and XHTML. In XHTML, scripts don't have a CDATA content type: the contents is treated exactly the same as any other element. It's not just a NetBeans issue.
So, there are several solutions:
Put the script in a separate file, so that its contents will not be mangled by the XML parser. This is the best solution, as it doesn't have any drawbacks. It works for HTML and XHTML.
Make sure the contents don't contain any < or & signs. Also make sure that editing the script will not introduce < or & signs later on. Replace them with their entity references: < and & respectively.
If the script doesn't contain ]]>, you can put the whole content in a <![CDATA[ .. ]]> block. This may even work in HTML in some browsers, but as <![CDATA[ is not formally defined as part of the HTML standard, this method is (officially) not HTML compatible.

Update a tbody's html with javascript (no lib): possible?

I want to update the contents of a TBODY (not the entire TABLE, because there's much more semi-meta data (LOL) in that). I get >= 0 TR's from the server (XHR) and I want to plump those in the existing table. The fresh TR's must overwrite the existing TBODY contents.
I've made a very simple, static example on jsFiddle that works in Chrome and probably all the rest, except for IE (I only use Chrome and test in IE8).
In Chrome, the very first attempt works: plump the TR's in the TBODY. No problem!
In IE it doesn't... I've included a not working example of what I had in mind to get it working.
I'm sure this problem isn't new: how would I insert a string with TR's in an existing TBODY?
PS. jQuery doesn't have a problem with this!? It's used here on SO. jQuery does something to the HTML and then inserts it as HTML nodes..? Or something? I can't read that crazy lib. It happens in this file (look for "html: function(". That's where the magic starts.
Anybody have a function or idea for this to work without JS library?
Here is a good resource about the problems of innerHTML and IE.
The bottom line is that on tbody the innerHTML property is readonly.
Here is a solution presented in one of the comments:
var innerHTML = "<tr><td>Hello world!</td></tr>";
var div = document.createElement("DIV");
div.innerHTML = "<table>" + innerHTML + "</table>";
// Get the tr from the table in the div
var trElem = div.getElementsByTagName("TR")[0];
Regarding the jQuery part of the question:
//inside the html() function:
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
//inside the empty() function (basically removes all child nodes of the td):
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
//append calls domManip applying this to all table rows:
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
//domManip as far as I can tell creates a fragment if possible and calls the three lines above with this=each row in turn, elem=the tbody(created if missing)
Using plain JavaScript, you can set the innerHTML property of the relevant element. The text that you set can contain a mix of HTML and text. It will be parsed and added to the DOM.

jQuery append DOM

All the examples of jQuery.append() seem to take an html string and append it to a container. I have a slightly different use case. My server returns me an XML that contains HTML text to be displayed, something like:
<event source="foo">
<contents>
<h1>This is an event</h1>
This is the body of the event
</contents>
</event>
I have a div where this content needs to be displayed.
My JS currently does the following:
Loads up the XML data into jQuery in the $.ajax() success handler:
var jData = $( data );
Find the contents tag and tries to add its children to the div that is supposed to display the event:
var contents = jData.find( "contents" );
if( contents != null )
{
$( contents ).children().each( function( index, value )
{
$( "#eventDiv" ).append( $( value ) );
});
}
The append() call fails with Uncaught Error: WRONG_DOCUMENT_ERR: DOM Exception 4 on Chrome. The debugger shows value to be a DOM Element object and $( value ) to be an Object that contains the Element.
Any help will be appreciated.
Thanks.
-Raj
You can't append nodes that belong to one DOM tree to another document.
Try to clone them:
$("#eventDiv").append( jData.find("contents").children().clone() );
or simply use their textual representation to have them re-created:
$("#eventDiv").append( jData.find("contents").html() );

jQuery + InnovaStudio WYSIWYG Editor

I am trying to avoid hard-coding each instance of this WYSIWYG editor so I am using jQuery to create an each() loop based on function name. Annoyingly InnovaStudio seems to explode when I try.
Documentation
Attempt #1
<script type="text/javascript">
/*
id = $(this).attr('id');
if(id.length == 0)
{
id = 'wysiwyg-' + wysiwyg_count;
$(this).attr('id', id);
}
WYSIWYG[wysiwyg_count] = new InnovaEditor('WYSIWYG[' + wysiwyg_count + ']');
WYSIWYG[wysiwyg_count].REPLACE(id);
*/
var demo = new InnovaEditor('demo');
demo.REPLACE('wysiwyg-1');
console.log('loop');
</script>
Effect
Works fine, but of course only works for a single instance of the editor. If I want multiple instances I need to use an each.
Attempt #2:
<script type="text/javascript">
var wysiwyg_count = 1;
//var WYSIWYG = [];
var demo;
(function($) {
$(function() {
$('.wysiwyg-simple').each(function(){
/*
id = $(this).attr('id');
if(id.length == 0)
{
id = 'wysiwyg-' + wysiwyg_count;
$(this).attr('id', id);
}
WYSIWYG[wysiwyg_count] = new InnovaEditor('WYSIWYG[' + wysiwyg_count + ']');
WYSIWYG[wysiwyg_count].REPLACE(id);
*/
demo = new InnovaEditor('demo');
demo.REPLACE('wysiwyg-1');
console.log('loop');
});
});
})(jQuery);
</script>
Effect
Replaces the entire HTML body of my page with JUST WYSIWYG related code and complains as no JS is available (not even Firebug, so can't debug).
Notice that I am hardcoding the name still. I only have one instance on the page I am testing it on, so when I get this hard-coded name working I will get the commented out code working along the same lines.
Does anybody know what the hell is going on here?
Solution: Don't bother trying to use InnovaStudio, went with CKEditor instead.
Even though you went for CKEditor you might be interested in a solution. You can supply a second argument to the REPLACE function. This second argument should also be a id, id from a element able to accept html output (like div, span, p).
demo = new InnovaEditor('demo');
demo.REPLACE('wysiwyg-1', 'wysiwyg-1-replaceDiv');
When the second argument is left out, InnovaStudio, writes the html output to the document by simply using:
document.write();
Hope this helps!
Why don't you use their own initialization code since version 4.3:
<textarea class="innovaeditor">
content here...
</textarea>
<script>
oUtil.initializeEditor("innovaeditor",
{width:"700px", height:"450px"}
);
</script>
The method is oUtil.initializeEditor(selector, option). The first parameter is selector and second is editor properties in JSON format.
The selector can be:
Css class name, if class name is specified all textareas with specified class name will be replaced with editor.
Textarea Id. If it is an Id, a prefix '#' must be added, for example oUtil.initializeEditor("#mytextarea").
Textarea object.
The second parameter is editor's properties. All valid editor's properties can be specified here for example width, height, cmdAssetManager, toolbarMode, etc.
Note that this method can be called from page onload or document ready event or during page load (as long as the object referred by selector are already rendered). This method available automatically when the page include the editor script.

Categories