XHTML Alternative to HTML5 Data Attributes
Introduction
I tend to write my own cross browser UI components and always strive to reduce the number of elements rendered in a page whilst also ensuring the mark-up validates. In situations where I need a key value pair but do not want to insert hidden fields, I use a custom CSS selector such as
<div id="mydiv" class="data-usedialogs-true">
prefix-key-value
I then have a script that executes when the page loads and goes through all (or selected) elements extracting the key value pairs and binding them to the actual element within the DOM.
This allows me to read/test the value using JavaScript without any manual parsing:
if (document.getElementById("mydiv").prefix.property=="true")
{
// do something...
}
This method is my w3c compliant alternative to the new HTML5 data attribute, whereby you can add custom data attributes to elements e.g.
<div id="mydiv" data-usedialogs="true">.
The good thing about this method is you can change the attribute, so you could have
<div id="mydiv" class="settings-autohide-true">
resulting in:
if (document.getElementById("mydiv ").settings.autohide=="true")
{
// do something...
}
How does the script work?
When the script executes it looks through the DOM for all elements with a class name matching the regular expression prefix-[A-Za-z0-9]{1,}- [A-Za-z0-9]{1,}. Once it finds an element, it then creates a custom attribute on that element and assigns an array containing the keys and values found within the matching selector(s).
This means you can have multiple key value pairs within the same element
<div id="mydiv" class="data-usedialogs-true data-autohide-true">
Allowing you to read the values back in JavaScript as:
if (element.data.usedialogs=="true")
{
// do something...
}
and
if (element.data.autohide=="true")
{
// do something...
}
The Script
//
// turns custom class names into key/value expando properties
//
// css class data-title-hello can be retrieved using element.data.title
//
function bindCssData(t /*tagName*/, p /*prefix*/)
{
p = p || "data";
t = t || "*";
var els = document.getElementsByTagName(t);
var reg = new RegExp("^(" + p + ")-([A-Z0-9]{1,})-([A-Z0-9]{1,})$", "i");
for (var i=0, l=els.length; i<l; i++)
{
var cssNames = (els[i].className != "") ? new String(els[i].className).split(' ') : [];
if (cssNames.length<=0) continue;
for (var ii=0, ll=cssNames.length; ii<ll; ii++)
{
var m = reg.exec(cssNames[ii]);
if (m && m.length >= 2) {
els[i][p] = els[i][p] || new Array();
els[i][p][m[2]] = m[3];
}
}
}
}
To use the script call bindCssData() from within your window.onload function. If you do not pass any parameters to the function, it will parse all elements looking for a prefix of data. To make this faster, consider calling the function with only the element types (tagName) you want to affect:
bindCssData("span");
or
bindCssData("span", "settings");
Anticipated Backlash -> Auto Response
Of course, there will be many designers/developers out there that will disagree with the concept of using CSS selectors to carry data to client side scripts. However, in my defence and with progressive enhancement in mind, this is the cleanest solution I could come up with without inserting unnecessary bloat into the page. In addition, the ability to define your own prefix reduces the potential of a conflict with actual page styles.
For example, you could an unnatural CSS selector such as __cssdata-key-value.
Feedback
I am always stupidly busy and don't get much time to knock-up these articles so they might be areas lacking explanation. If you feel I need to expand/correct anything please leave a comment and I will update it as soon as I can.
发表评论
"I do agree with all the ideas you have presented in your post. They are very convincing and will definitely work. Thanks for the post."
"You built some beneficial details there. I did a look for within the matter and observed most folks will consent with your webpage."
"I hope you will keep updating your content constantly as you have one dedicated reader here."
"How did you make this template? I got a blog as well and my template looks kinda bad so people don�t stay on my blog very long."
""Hi. I go through a few of one�s other posts and wished to understand in the event you would be interested in exchanging blogroll links?"
"You really make it seem so simple with your presentation but I find this topic before really hard to understand. It seems too complicated and very broad for me. I am looking forward for your next post."
"How did you make this template? I got a blog as well and my template looks kinda bad so people don�t stay on my blog very long."
"I�ve bookmarked this because I found it interesting. I would be very interested to hear more news on this. Thanks!"
"When i visit a blog, chances are that i get disappointed. Regarding your blog,I have to say that you have done a good job here."
"Interesting read perhaps the best article iv e browse today We learn everyday cheers to you"
"I recently came across your web site and have been reading along. I thought I would leave my very first comment. Nice blog! I will keep visiting this website very frequently."
"Real nice design and wonderful content material, nothing else we want"
"Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very"
"Thanks for this, it was actually an useful stuff and I will look back here for some more soon"
"I had difficulty looking at this in Firefox but it works fine in IE. Anway, the content is good. I am very happy to have come across this."
"It is really a nice and useful piece of info. I�m glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing."
"I think you have a great page here� today was my first time coming here.. I just happened to find it doing a google search. anyway, good post.. I�ll be bookmarking this page for sure."
"5 star article brilliant. I am new to blogging and you used a langauge I can understand"
"You completed a few nice points there. I did a search on the topic and found nearly all folks will consent with your blog."
"As a Newbie, I am constantly exploring online for articles that can be of assistance to me. Thank you"
"That�s kinda amazing stuff. It�s weird how sometimes random Internet surfing can get me in places like this, where really cool things can be found. I�ll be back"
"Real nice design and wonderful content material, nothing else we want"
"Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate?"
"I�ve bookmarked this because I found it interesting. I would be very interested to hear more news on this. Thanks!"
"Wonderful blog! I genuinely love how it is easy on my eyes and also the facts are well written. I am wondering how I may be notified whenever a new post has been made. I have subscribed to your rss feed which ought to do the trick! Have a nice day!"
"Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I�ll be subscribing to your feed and I hope you write again soon!"
"I like the valuable information you provide in your articles. I�ll bookmark your weblog and check again here frequently. I�m quite certain I�ll learn lots of new stuff right here! Best of luck for the next!"
"I ve read some good stuff here Definitely worth bookmarking for revisiting"
"It is really a nice and useful piece of info. I�m glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing."
"You got your point here, hehe, you surely did. In moments like this, I think that �the WEB� is the greatest invention of all human inventions. Or at least it�s most entertaining one!"
"You built some beneficial details there. I did a look for within the matter and observed most folks will consent with your webpage."
"Hello, this is my first time i visit here. I found so many interesting in your blog especially on how to determine the topic. keep up the good work."
"Good blog, where did you come up with the knowledge in this piece of content? I??m glad I found it though, ill be checking back soon to see what other articles you have."
"Interesting read perhaps the best article iv e browse today We learn everyday cheers to you"
"This is a good, common sense article. Very helpful to one who is just finding the resouces about this part. It will certainly help educate me."
"I hope you will keep updating your content constantly as you have one dedicated reader here."
"Cool post! How much stuff did you have to look up in order to write this one? I can tell you put some work in."
"Good blog, where did you come up with the knowledge in this piece of content? I??m glad I found it though, ill be checking back soon to see what other articles you have."
"hopefully this comment doesn�t appear multiple times (it appears to freeze once i try to post my comment.. not certain if it�s really posting), but all I truly wanted to say was great post and thanks for sharing."
"Perhaps this is one of the most interesting blogs that I have ever seen. Interesting article, Funny comment. Keep it up!"
"How did you make this template? I got a blog as well and my template looks kinda bad so people don�t stay on my blog very long."
"This is very intreresting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your great post."useful."
"I do agree with all the ideas you have presented in your post. They are very convincing and will definitely work. Thanks for the post."
"Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I�ll be subscribing to your feed and I hope you write again soon!"
"I cannot subscribe to your rss feed for some reason. I�m using google reader by the way."
"It is a great uplifting article.We are pretty much happy about your great work.You put genuinely very helpful details. Keep it up. Retain blogging. Aiming to reading the next post."
"Just saying thanks will not just be sufficient, for the tremendous lucidity in your writing. I will right away grab your rss feed to stay abreast of any updates."
"It is really a nice and useful piece of info. I�m glad that you shared this helpful information with us. Please keep us informed like this. Thanks for sharing."
"Interesting read perhaps the best article iv e browse today We learn everyday cheers to you"
"When i visit a blog, chances are that i get disappointed. Regarding your blog,I have to say that you have done a good job here."