Returning metadata with CSS - javascript

I have a CSS stylesheet that's dynamically created on the server, and returned via a <link> tag. Is it possible to return any metadata with this stylesheet, that I could read with JavaScript?
(The use case: the stylesheet I return is a combination of several smaller ones. I want my JavaScript code to be able to detect which smaller ones were included.)
I considered adding some custom properties to an element:
body {
-my-custom-prop1:0;
-my-custom-prop2:0;
}
But when I try to read these with:
window.getComputedStyle(document.body)['-my-custom-prop1']
they're not returned. Any other ideaas?
EDIT: I ended up taking a slightly different approach. Instead of adding a <link> tag, I made an AJAX request to get the stylesheet, and added its text to a <style> tag. This way I could use the HTTP response headers to include metadata. Of course, this won't work across domains, like a <link> tag does.

See example of the following →
Though I think this technique is ill-advised, here's something I developed that I've tested to work in Chrome, FF, Safari and IE8.
First, I picked the list-style-image property to be used to store the meta data since it can contain any string in the url() parameter and yet wasn't going to be used under any normal circumstances in the body CSS.
Then I implemented a common cross-browser function to getComputedStyle since this isn't available in all browsers.
Then I parsed the return property to get only the data within the url(''), resulting in these functions:
var getStyle = function(el, cssprop) {
if (el.currentStyle) {
return el.currentStyle[cssprop];
} else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el, "")[cssprop];
} else {
return (el.style) ? el.style[cssprop] : 0;
}
};
var pullCSSMeta = function() {
var aMeta = getStyle(document.body, 'listStyleImage').split('/'),
meta = aMeta[aMeta.length - 1];
return decodeURIComponent(meta.substr(0, meta.length - 1).replace(/"$/,''));
};
If you need to store more than one piece of information you could comma-delineate the data or potentially even store a JSON string. I hope you have a good reason for wanting to do this as I think there are better ways to store meta data... but there you go!
See example →

The returned object actually represents the CSS 2.1 used values, not the computed values. https://developer.mozilla.org/en/DOM/window.getComputedStyle
You might be able to interrogate these styles via another method though:
http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript

I asked a related question a while ago. It turns out that you have to parse the stylesheet text manually with javascript. I decided it was not worth the bother and found a different solution to my problem. You could use some clever tricks like standard properties on bogus classes would work I guess.

Related

Convert css styles to inline styles with javascript keeping the style units

We have a corporate content management system that allows for rich text editing/html markup, but does not allow for head elements or style sheets to be uploaded, attached, or used in any way. It provides some rich text editing controls and also access to the source html, but just for the html fragment -- there is no head, no body. We also have no access the whole system that presents these bits of markup on the page. The only way to style the content is through inline style attributes on the elements. It is best, it isn't pretty, but that is what we have and I'm trying to make the best of a bad situation.
We also have high standards for visual presentation and would like to be able to quickly produce and modify/update content and keep it looking nice. It is difficult to correctly apply formatting using the system. For anybody who has tried to markup anything more than a paragraph or two with an RTE, you probably know what I mean. It seems like we should have a different system, but has anybody worked for a large company before? Just sayin.
We do have access to another location where we could "author" and "store" actual styled content and then "compile it" for copypasta into the other system. In other words, we could author/design using css and best practices and then we could run some code that could convert those element, class, and id formatting into inline styles.
I did my research and found this thread which also lead me to this code.
These both are very helpful in exploring solutions, but I've run into an issue. These solutions use the javascript getComputedStyle() method. There are some other options for properties to only look at other properties or to be recursive on the children of the element provide, but basically it boils down to this. (Since getComputeStyle returns an object and not an array, there is also a prototype/polyfill to allow iterating over an object with forEach, but none of that is part of the issue I'm facing.)
const computedStyle = getComputedStyle(element);
computedStyle.forEach(property => {
element.style[property] = computedStyle.getPropertyValue(property);
});
This works well for css attributes like font-size:24px or margin:0 15px. The issue I'm running into are when I'm using units other than px. For example, if I'm trying to make something that has width:50%. getComputedStyle() converts the 50% to the actual number of pixels that 50% is currently using.
In the notes section of the MDN web docs I see that this is expected behavior. Although I'm not quite clear on what that last line means.
...An example difference between pre- and post-layout values includes the
resolution of percentages for width or height, as those will be
replaced by their pixel equivalent only for used values.
So what I'm trying to do is convert something like this
.container{width:50%;}
<div class="container">
into something like this
<div class="container" style="width:50%">
Does anyone know of a way to complete this type of transformation?
PS: If it matters we'll be using the more basic attributes in our css -- no transitions, grid, prefixing, etc. We still need to support IE 11 -- if that tells you anything. We won't need to account for every edge case or browser. Just some basic stuff so that all our H1 look the same.
Couldn't find any way to do this using the built in getComputedStyle(). It also returned too many properties that I wasn't interested in. So I came up with a different approach. Basically to use the same function to loop through an element (and maybe all its children elements) and the use Element.matches() to get all the css rules that apply to the element and apply the properties as they were specified in the stylesheet.
I modified this answer a bit to get the rules from the stylesheet.
Has the added benefit that we can pull either from all the document stylesheets or just from a specific one that is needed for preparing the code to go into our content management systems's rich text editor.
function applyInline(element, recursive = true) {
if (!element) {
throw new Error("No element specified.");
}
const matches = matchRules(element);
// we need to preserve any pre-existing inline styles.
var srcRules = document.createElement(element.tagName).style;
srcRules.cssText = element.style.cssText;
matches.forEach(rule => {
for (var prop of rule.style) {
let val = srcRules.getPropertyValue(prop) || rule.style.getPropertyValue(prop);
let priority = rule.style.getPropertyPriority(prop);
element.style.setProperty(prop,val,priority);
}
});
if (recursive) {
element.children.forEach(child => {
applyInline(child, recursive);
});
}
}
function matchRules(el, sheets) {
sheets = sheets || document.styleSheets;
var ret = [];
for (var i in sheets) {
if (sheets.hasOwnProperty(i)) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (el.matches(rules[r].selectorText)) {
ret.push(rules[r]);
}
}
}
}
return ret;
}

Removing Chrome's "translate" DOM Property

I'm working with some legacy code where the original developers made heavy use of generating HTML DOM nodes with a non-standard attribute named translate
<span translate="[{"shown":"My Account","translated":"My Account","original":"My Account","location":"Text","scope":"Mage_Customer"}]">My Account</span>
and then traversing/searching for those nodes with javascript code like the following.
if (!$(target).match('*[translate]')) {
target = target.up('*[translate]');
}
The problem I'm trying to solve is, it appears that Google Chrome automatically adds a translate attribute to every DOM node in the document, and that this DOM node's value is a boolean true. You can see this by running the following Javascript from Chrome's javascript console
> document.getElementsByTagName('p')[0].translate
true
>
Is there anyway to tell Chrome not to populate these attributes? Their presence is wrying havoc with the legacy code. PrototypeJS's match and up nodes treat these boolean object attributes as matches, while the code I'm dealing with is specifically looking for DOM nodes with an attribute named translate. I'd like to find a solution for my problem that doesn't involved rewriting the old Javascript to use methods like hasAttribute.
I tried (as a wild guess) adding the meta attributes mentioned in this article,
<meta name=”google” value=”notranslate”>
<meta name=”google” content=”notranslate”>
but the nodes in the page still has a boolean true translate attribute.
(if it matters, this is Magento's inline translation system I'm talking about here)
The best I've been able to come up with so far is going through every DOM element in the page defining a getter that checks for the existence of an attribute. (the Object.__defineGetter__ guard clause ensures no errors in browsers that don't support modern Javascript)
if(Object.__defineGetter__)
{
var hasTranslateAttribute = function(){
return $(this).hasAttribute("translate");
};
document.observe("dom:loaded", function() {
$$('*').each(function(theElement){
theElement.__defineGetter__("translate", hasTranslateAttribute);
});
});
}
I tried defining a getting on Object.prototype and Element.prototype, but it seems like the browser's native translate is defined higher up the chain, so you need to redefine things on a per element basis.
Replace the nonstandard attribute translate by an attribute like data-translate, which is virtually guaranteed to be and to remain undefined in HTML specifications and in browsers. The data-* attributes were invented to prevent issues like this, and they can also be used to fix them.

Using $.data() in jQuery to store flag on element

I am authoring a simple jQuery plugin that turns an input tag into a time-formatted element (on blur it will change 245p into 2:45 pm).
Since I do not want to apply the time format events to the same element twice, I need a way to detect that the specific element in the list provided has not already had the format applied.
This is the relevant part of the code:
var methods = {
init : function(sel) {
var $this = $(sel);
return $this.each(function(){
var data = $(this).data('time_formatted');
if (data) {
return;
} else {
$(this).data('time_formatted', true);
I have heard that using $(sel).data() in a plugin is not a good idea; instead, use $.data(). I don't know why, that's just what I've heard; honestly, I don't know what the difference is.
So my question is, is this the way to accomplish checking if a specific element has had the time formatter applied to it in a plugin?
If you care to see the plugin in it's current development state, see http://jsfiddle.net/userdude/xhXCR/.
Thanks!
Jared
Where have you heard that using .data() is not good? jQuery's plugin autoring page says:
Often times in plugin development, you may need to maintain state or check if your plugin has already been initialized on a given element. Using jQuery's data method is a great way to keep track of variables on a per element basis. However, rather than keeping track of a bunch of separate data calls with different names, it's best to use a single object literal to house all of your variables, and access that object by a single data namespace.
So it should be perfectly fine.

In DOM is it OK to use .notation for getting/setting attributes?

In DOM, is it OK to refer to an element's attributes like this:
var universe = document.getElementById('universe');
universe.origin = 'big_bang';
universe.creator = null;
universe.style.deterministic = true;
? My deep respect for objects and their privacy, and my sense that things might go terribly wrong if I am not careful, makes me want to do everything more like this:
var universe = document.getElementById('universe');
if(universe.hasAttribute('origin')) then universe.origin = 'big_bang';
etc...
Is it really necessary to use those accessor methods? Of course it may be more or less necessary depending on how certain I am that the elements I am manipulating will have the attributes I expect them to, but in general do the DOM guys consider it OK to use .notation rather than getters and setters?
Thanks!
For XML documents, you must use getAttribute/setAttribute/removeAttribute etc. There is no mapping from JavaScript properties to DOM attributes.
For HTML documents, you can use getAttribute et al to access attributes, but it's best not to because IE6-7 has difficulties with it. The DOM Level 2 HTML properties are not only more reliable, but also easier to read.
It's unclear whether you're using XML or HTML documents here. Clearly origin is not an HTML attribute; ‘custom’ elements and attributes like this should not be included in HTML documents. But it's unclear what universe.style.deterministic refers to; you wouldn't get a CSS style lookup mapped without an HTML style attribute.
Yes, it's fine ;-)
If there's an attribute in the DOM, you can set it or get it, directly.
No private or read-only elements or anything. By the way, JavaScript doesn't have a 'then' keyword.
Due to cross browser issues I always use getAttribute and setAttribute:
if(!universe.getAttribute('origin'))
{
universe.setAttribute('origin', 'big_bang');
}
I don't recall the specifics but I have had problems with the property style universe.origin and dynamically created DOM elements.
No, it's not fine to do so. Most properties of DOM objects can be overwritten. You won't ruin the browser's behavior, since it doesn't use the DOM API. But you will ruin your JS scripts if they attempt to use the overwritten property in its original meaning.
My own way of doing things, when I have several attributes to attach to an object (as opposed to a single flag or link), is to create a custom object and then link it from the DOM element:
var Universe = {
origin: "big_bang",
creator: null,
style: { deterministic: true }
};
document.getElementById('universe')._universe = Universe;

Javascript attributes compact

Is there a way to assign attributes in a more compact manner
I dont really want to use setAttribute as it seems to be buggy in ie8
This list is for all attributes so its quite long
else if(a=="textalign")
{
e.style.textAlign="";
e.align=v
}
if(a=="textalign")
{
e.style.textAlign="";
e.align=v
}
I don't know why you are trying to set alignment via an HTML attribute rather than just using the CSS... this is much less reliable as there are many elements which have no align attribute. HTML align is also deprecated and should be avoided in general.
You don't say what the “other attributes” are that you might want to set. If you are talking specifically about HTML attribute properties it's easy to set them by a name in a string:
e[a]= v;
But then you need a to be the HTML attribute property name, which would be ‘align’ not ‘textalign’. It wouldn't do anything special to try to workaround CSS overrides like textAlign, because there is no automated way to do that, and the interaction between the deprecated HTML styling attributes and CSS is ill-defined. Stick to attributes or CSS (CSS is highly preferable); don't use both.
If you are talking about setting any CSS style property, as I might guess from the name being ‘textalign’, that's done similarly:
e.style[a]= v;
But then, again, you'd want to be using the exact style property name ‘textAlign’ not ‘textalign’.
If you want to set CSS style properties by their CSS name, like ‘text-align’, you could transform that to the DOM name automatically:
// convert foo-bar-baz to fooBarBaz
//
var doma= a.replace(/-([a-z])/g, function(m, g) {
return g.toUpperCase();
});
e.style[a]= v;
If you really do need to use case-lossy names like ‘textalign’ you'd have to use a lookup of all property names you wanted to use to get the case back:
var propernames= ['textAlign', 'borderColor', 'paddingTop']; // etc
for (var i= propernames.length; i-->0;)
if (propernames[i].toLowerCase()===a)
a= propernames[i];
e.style[a]= v;
Forget setAttribute. It has nothing to do with style properties (it's a bug in IE6-7 that it even works on styles there), and you shouldn't use it on elements either for HTML documents, as there are other IE6-7 bugs to contend with there. Stick to the ‘DOM Level 2 HTML’ direct property access stuff, which is more reliable and easier to read.
Use a class instead of giving all the attribute values.
.testClass
{
// set all attribute values here
}
e.className = "test";
See
element.className
Use some framework such as JQuery, it takes care of all of your browser incompatibility issues. In JQuery you use the .css('attributeName', 'value')method.
jQuery would make that easy with .attr({attr1: val, attr2: val}) etc. It would also shield you from many cross-browser compatibility bugs.

Categories

Resources