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 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."
"Hi. I wanted to drop you a quick note to express my thanks. I�ve been following your blog for a month or so and have picked up a ton of good information as well as enjoyed the way you�ve structured your site. I am attempting to run my own blog but I think its too general and I want to focus more on smaller topics. Being all things to all people is not all that its cracked up to be."
"I ve read some good stuff here Definitely worth bookmarking for revisiting"
"I think this is one of the most important information for me. And im glad reading your article. Good job, cheers"
"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"
"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."
"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 useful."
"Great stuff from you, man. Ive read your stuff before and youre just too awesome. I love what youve got here, love what youre saying and the way you say it. You make it entertaining and you still manage to keep it smart. I cant wait to read more from you. This is really a great blog."
"Interesting read perhaps the best article iv e browse today We learn everyday cheers to you"
"5 star article brilliant. I am new to blogging and you used a langauge I can understand"
"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."
"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."
"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"
"Took me time to learn all of the comments, however I really enjoyed the article. It proved to be Very useful to me and I�m positive to all of the commenters here! It�s always nice when you can�t solely be told, but in addition entertained! I�m positive you had enjoyable penning this article."
"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"
"Hello There. I found your blog using msn. This is an extremely well written article. I will be sure to bookmark it and return to read more of your useful info. Thanks for the post. I�ll certainly return."
"Real journalist work and helpful summary. It�s amazing how good quality info can be found in the dark alleys of the internet "
"Real journalist work and helpful summary. It�s amazing how good quality info can be found in the dark alleys of the internet "
"You can definitely see your enthusiasm in the work you write. The world hopes for more passionate writers like you who aren�t afraid to say how they believe. Always go after your heart."
"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!"
"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."
"I ve read some good stuff here Definitely worth bookmarking for revisiting"
"Hi. I wanted to drop you a quick note to express my thanks. I�ve been following your blog for a month or so and have picked up a ton of good information as well as enjoyed the way you�ve structured your site. I am attempting to run my own blog but I think its too general and I want to focus more on smaller topics. Being all things to all people is not all that its cracked up to be."
"Interesting read perhaps the best article iv e browse today We learn everyday cheers to you"
"I cannot subscribe to your rss feed for some reason. I�m using google reader by the way."
"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."
"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."
"I usually don�t post in Blogs but your blog forced me to, awesome work, stunning"
"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."
"Helpful information. Lucky me I found your site accidentally, and I am shocked why this coincidence did not took place in advance! I bookmarked it."
"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."
"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."
"Real journalist work and helpful summary. It�s amazing how good quality info can be found in the dark alleys of the internet "
"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 have been examinating out a few of your posts and i must say pretty clever stuff. I will surely bookmark your website"
"I permanently wanted to write on my site something like that. but I dont know how to start , I am so lucky found your blog site"
"Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information."
"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."
"5 star article brilliant. I am new to blogging and you used a langauge I can understand"
"As a Newbie, I am constantly exploring online for articles that can be of assistance to me. Thank you"
"Hi. I wanted to drop you a quick note to express my thanks. I�ve been following your blog for a month or so and have picked up a ton of good information as well as enjoyed the way you�ve structured your site. I am attempting to run my own blog but I think its too general and I want to focus more on smaller topics. Being all things to all people is not all that its cracked up to be."
"Real journalist work and helpful summary. It�s amazing how good quality info can be found in the dark alleys of the internet "
"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 think this is one of the most important information for me. And im glad reading your article. Good job, cheers"
"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"
"Hello there, You have done an incredible job. I will certainly digg it and personally suggest to my friends."
"I hope you will keep updating your content constantly as you have one dedicated reader here."
"Great stuff from you, man. Ive read your stuff before and youre just too awesome. I love what youve got here, love what youre saying and the way you say it. You make it entertaining and you still manage to keep it smart. I cant wait to read more from you. This is really a great blog."
"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 useful."
"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!"