Tuesday, October 16, 2012

building custom tags in html5 and javascript, part 1

If you've had the chance to work with Facebook's Social Plugins, you've likely come across the option to embed their widgets using XFBML. They offer a similar "HTML5 compatible" option, but I tend to think the custom, name-spaced tags option is neat. So, let's explore one way to do that.

As an example of the usefulness, I'll use my recently completed book of small potatoes (wisdom of the ancients) from thepointless.com. With each wise guy quote, we see markup in the following format, which renders a voting widget, with the help of some fancy JavaScript:

<tpdc:voter method='/ajax/pointlisting_vote' record_id='37' vote='1'
 fb_like_url='http://www.thepointless.com/pointlistings?id=37'>
  <tpdc:vote>vote<tpdc:vote>
  <tpdc:unvote>unvote<tpdc:unvote>
  +<tpdc:count>1<tpdc:count>
<tpdc:voter>


(Rather the post the full script that does the magic here, I'll be using some trivial simplified JavaScript here for conciseness. You can take a peek at it in action if you're interested.)

To prevent Internet Explorers 7 and 8 from giving us the silent treatment come script-time, our custom tags need to live in a namespace. (Other browsers, as far as I know, ignore the namespace altogether.) And the namespace must be defined in the opening html tag:

<html xmlns:tpdc="http://www.thepointless.com/ns/tpdc">

Now, as you might imagine, a little JavaScript magic is needed to work with these nodes gracefully. And although a touch hacking, it may not be as hackish as you'd expect! As seen on the thepointless.com, here is the function we use to grab these nodes and "import" their attributes correctly:

var getNodes = function(n, q) {
    try {
        // i think "r" stands for "return" here.

        // in any event, our first step is to try to find the nodes
        // by their full names -- that is, with the namespace.
        var r = n['getElementsByTagName'](q);
        if (r.length < 1) {

            // ... and if we don't find anything, omit the namespace,
            // if present.
            var p = q.split(":");
            if (p.length == 2) {
                r = n['getElementsByTagName'](p[1]);
            }
        }

        // import attributes, for each node
        for (var i = 0; i < r.length; i++) {


            // for each attribute in r[i]

            // first, make sure we're not attempting to RE-import attributes.
            var ri = r[i];

            if (!ri.__attributes_imported) {

                // so, we basically iterate through each attribute and
                // "re-attach" it to the node directly. seems silly, but
                // it allows our scripts to operate on these attributes
                // later much more naturally.
                for (var ai = 0; ai < ri.attributes.length; ai++) {
                    var att = ri.attributes[ai];
                    if (!ri[att.name]) {
                        ri[att.name] = att.value;
                    }
                }
                ri.__attributes_imported = true;
            }
        }

        // and finally, give that list of nodes back.
        return r;
    } catch (e) {
        return [];
    }
} // getNodes()


This getNodes() implementation works in recent versions of Chrome, Firefox, Safari, and IE7+ (not tested in IE6). One-off use of the function works similarly to (but not exactly like) the normal getElementByTagName() function. So, if we want to work with all the tpdc:voter nodes, we could do this:

// get an array of tpdc:voter nodes.
var voterNodes = getNodes(document, "tpcd:voter");

// for each one, let's add an onclick event that simply displays
// the method attribute.
for (var i = 0; i < voterNodes.length; i++) {

  // to be clear, the "this" here is the node itself
  voterNodes[i].onclick = function() { alert(this.method); }
}


Pretty simple. And working with child nodes is just as easy. Suppose we want to loop through all the tpdc:voter nodes and make each tpdc:count node with a value of 10 or more bold. Now, with this trivial example, we could do this globally, like so:

// get all the tpdc:count nodes.
var countNodes = getNodes(document, "tpdc:count");

// make each one with an innerHTML value >= 10 bold
for (var i = 0; i < countNodes.length; i++) {
  if (parseInt(countNodes[i].innerHTML) >= 10) {
    countNodes[i].style.fontWeight = 'bold';
  }
}


Or, we can work within the context of a single tpdc:voter node, as we might in a voter node's class method. A trivial example again, but this works as expected:

// assume we already have a tpdc:voter node, voterNode
var countChildren = getNodes(voterNode, 'tpdc:count');
// act on all tpdc:count nodes found.
for (var ci = 0; ci < countChildren.length; ci++) {
  if (parseInt(countChildren[ci].innerHTML) >= 10) {
    countChildren[ci].style.fontWeight = 'bold';
  }
}


Neat.

But, we're not done yet. What we really want is the ability to treat these custom tags like instances of a real class. And we can! We can define a namespace (empty object) with some classes (functions) and bind them semi-automagically to the DOM nodes.

Let's consider a TPDC namespace with two very simple classes:

// the namespace
var TPDC = {};


// class Simple
TPDC.Simple = function() {
  // we can do things at object "instantiation" time
  this.innerHTML = "Simple";
} // class TPDC.Simple()

// class LessSimple
TPDC.LessSimple = function() {

  // we can also define object methods
  this.makeSimple = function() {
    this.innerHTML = "Simple";
  } // TPDC.LessSimple.makeSimple()

  this.onClick = function() {
    this.makeSimple();
  } // TPDC.LessSimple.onClick()

  this.innerHTML = "Less Simple";
} // class TPDC.LessSimple()


Simple. And so is binding our whole TPDC "namespace" to the appropriate document nodes:

for (var k in TPDC) {
  var tpdc_nodes = getNodes(document, 'tpdc:' + k);
  for (var i = 0; i < tpdc_nodes.length; i++) {
    TPDC[k].apply(tpdc_nodes[i]);
  }
}


And, if we want to stuff our getNodes() function stuffed neatly away in a shared library, we can also add a convenient little binder method:

var BindNS = function(ns_name, parent) {
  // "find" the namespace within its parent, given its name
  var p = parent || this;
  var ns = p[ns_name];


  // apply the class constructors to the document nodes
  for (var k in ns) {
    var ns_nodes = getNodes(document, ns_name.toLowerCase() + ":" + k.toLowerCase());
    for (var i = 0; i < ns_nodes.length; i++) {
      ns[k].apply(ns_nodes[i]);
    }
  }
} // BindNS()


And then bind our simple TPDC class with one line:

BindNS('TPDC');

And at this point, any tags in our document that look like these will operate as though they're instances of our Simple and LessSimple classes:

<tpdc:simple>weeeeee...</tpdc:simple>
<tpdc:lesssimple>...eeeeee!</tpdc:lesssimple>


They also operate as generic DOM nodes too, of course. Your JavaScript classes are, in many respects, subclasses of the Node class.

Two things to remember though:

1. Most browsers ignore the namespace. So, this approach doesn't grant you an ability, so far as I know, to create namespaces with identical class names. You can work around this by including the namespace again as a prefix in your class names if you need to.

  and

2. It's invalid markup! It's served up with a text/html content type and an HTML5 doctype, which explicitly forbids tag namespaces. So, you might even call it grossly invalid! That said, of all the custom tag variations I tested, this syntax actually provided the most consistent behavior.

In any event, I like the way this works. I can simplify and minimize both my markup and my script using this approach. And I definitely plan on playing with it more. One thing I'm pondering is an elegant way to automagically attach custom child tags to custom-tag parents in a helpful and meaningful way.

So, if anyone has any thoughts on that (or any of this), I'd be interested in your feedback.

And of course, I encourage you to check out the working examples of this concept at thepointless.com, starting with the book of small potatoes!

Wee!

UPDATE: There's now a building custom tags in html5 and javascript, part 2!

108 comments:

  1. become a new player in the casino good top online casinos I understood, I understood that on this site, luck will smile at me

    ReplyDelete
  2. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too..
    Oracle DBA Online Training

    ReplyDelete
  3. 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

    Tableau online training

    ReplyDelete
  4. Thanks for such a great article here. I was searching for something like this for quite a long time and at last I’ve found it on your blog. It was definitely interesting for me to read about their market situation nowadays.
    Sql server dba online training

    ReplyDelete
  5. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me.

    ReactJS Online Training

    ReplyDelete
  6. Howdy! I could have sworn I’ve been to this blog before but after looking at many of the posts I realized it’s new to me. Regardless, I’m certainly delighted I discovered it and I’ll be book-marking it and checking back often!
    Tech geek

    ReplyDelete
  7. Thanks for sharing such a great information. Its really nice and informative sql training
    and ms sql server tutorial.

    ReplyDelete

  8. This post is really nice and informative. The explanation given is really comprehensive and informative. I want to share some information about the best oracle dba training and weblogic server tutorial training videos. Thank you .Hoping more articles from you.

    ReplyDelete
  9. This web site truly has all the information and facts I needed concerning this web site subject and didn’t know who to ask.

    ReplyDelete
  10. Good article! I found some useful educational information in your blog about React Js, it was awesome to read, Java training in chennai thanks for sharing this great content to my vision
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  11. Paid marketing can be an excellent way to increase your visibility and conversion rates. Resurge Pills

    ReplyDelete
  12. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.

    vmware training in bangalore

    vmware courses in bangalore

    vmware classes in bangalore

    vmware training institute in bangalore

    vmware course syllabus

    best vmware training

    vmware training centers

    ReplyDelete
  13. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.

    Tableau Online Training

    Tableau Classes Online

    Tableau Training Online

    Online Tableau Course

    Tableau Course Online

    ReplyDelete
  14. I read this article. I think You put a lot of effort to create this article. I appreciate your work. Van Helsing Coat

    ReplyDelete
  15. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    https://www.3ritechnologies.com/course/microsoft-azure-training-in-pune/

    ReplyDelete
  16. Awesome blog with unique content and knowledgeable information thanks for sharing.

    typeerror nonetype object is not subscriptable

    ReplyDelete
  17. Fantastic article with top quality information found very useful thanks for sharing
    Data Science Course in Hyderabad

    ReplyDelete
  18. I found Habit to be a transparent site, a social hub that is a conglomerate of buyers and sellers willing to offer digital advice online at a decent cost. PMP Training in Hyderabad

    ReplyDelete
  19. This post is great. I really admire your post. Your post was awesome. data science course in Hyderabad

    ReplyDelete
  20. I just want to say it`s wonderful blog.Photo editing company.

    ReplyDelete
  21. In addition to educational software, Python is also a favored language for use in AI tasks. Because Python is a scripting language with rich text processing tools, module architecture, and syntax simplicity, data science course in india

    ReplyDelete
  22. Free software has two unique major problems that have influenced my design decisions, because often they are avoidable and can make software less robust, less usable, and harder to maintain. best Flask course

    ReplyDelete
  23. I like to share my AWS Training in chennai from the best and experienced AWS cognex trained and become the expert in AWS training in Chennai

    ReplyDelete
  24. As always your articles do inspire me. Every single detail you have posted was great.
    data science in malaysia

    ReplyDelete
  25. This post is very simple to read and appreciate without leaving any details out. Great work!
    data scientist malaysia

    ReplyDelete
  26. This is my first time visit here. From the tremendous measures of comments on your articles.I deduce I am not only one having all the fulfillment legitimately here!
    data science courses in noida

    ReplyDelete
  27. I have bookmarked your site since this site contains important data in it. I am truly content with articles quality and introduction. Much obliged for keeping extraordinary stuff. I am a lot of grateful for this site.
    data scientist training and placement in hyderabad

    ReplyDelete

  28. That is nice article from you, this is informative stuff. Hope more articles from you . I also want to share some information about bw Training

    ReplyDelete
  29. FOXZ88.NET online casino website Global standard 2020-2021
    คาสิโนออนไลน์


    Betting online gambling reminiscent of UFASCR.COM Baccarat.
    ufabet


    UFABET football betting website, the big brother of all UEFA networks, UFADNA, with an update The first modern system in 2021
    ufa


    Web football i99PRO online lottery casino apply today for free 5000 bonus
    เว็บบอล


    Kardinal Stick Siam - Relx a great promotion. Express delivery in 3 hours.
    relx

    ReplyDelete
  30. The content that I normally go through nowadays is not at all in parallel to what you have written. It has concurrently raised many questions that most readers have not yet considered.
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

    ReplyDelete
  31. Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post.Keep up your work
    data scientist training in hyderabad

    ReplyDelete
  32. This website and I conceive this internet site is really informative ! Keep on putting up!
    best data science course online

    ReplyDelete
  33. Great Information..

    https://localdrivingacademy.com.au/driving-school-frankston

    ReplyDelete
  34. Always so interesting to visit your site.What a great info, thank you for sharing. this will help me so much in my learning
    artificial intelligence course

    ReplyDelete
  35. Pretty section of content. I just stumbled upon your website and in accession capital to assert that I get in fact enjoyed account your blog posts. Any way I’ll be subscribing to your feeds and even I achievement you access consistently quickly. บาคาร่าออนไลน์

    ReplyDelete
  36. Keep you data more safe and accurate by the help of Fungible. Because they are company technology based and DPU™-based technology and solutions that will enable highly performant, efficient, reliable and secure data centers to be built at any scale.

    ReplyDelete
  37. Hello there! I simply wish to offer you a major approval for your incredible data you have here on this post. I will be returning to your site for all the more soon.best interiors

    ReplyDelete
  38. Amazing article,Surely, you must have done great research for this article. I learned a lot from it. Thanks for sharing this article.
    by cognex is the AWS Training in chennai

    ReplyDelete
  39. The leather jacket mens is not really a men’s staple. However, it can be a very personal piece that will follow you for years to come, provided you choose it clearly.
    MR.STYLES suppliers of leather Fashion Jackets,dauntless leather jacket,Harley Davidson Leather Jacket,Motorcycle Leather Jacket with custom design the best quality of Cowhide, Sheep, Lamb, And Goat Skins. Save your cash and enjoy the best quality. Best Men’s Leather Jackets with mr-styles.com

    ReplyDelete
  40. Leather fashion jacket never runs out of style and if you’re looking for best articles regarding Harley Davidson leather Jackets, you’re just at the right place.
    JnJ is a registered firm that deals with all kinds of leather jackets, including motorbike racing suits, motorbike leather jackets and leather vests, leather gloves, for both men and women.

    ReplyDelete
  41. Awesome article. I enjoyed reading your articles. this can be really a good scan for me. wanting forward to reading new articles. maintain the nice work!


    Data Science Training in Hyderabad

    ReplyDelete
  42. This is such a great post, and was thinking much the same myself. Another great update…

    Data Science Training in Hyderabad

    ReplyDelete
  43. B3 Bomber Jacket For Sale - Free Shipping and Best Deal
    Men consistently partial to skins and hides due to the fact the start of timethey utilized it to insure by themselves and safeguard them by your cold temperatures.
    Now shearling leather coats, Real Leather Bomber Jackets, Buy Harley Davidson Leather Motorcycle Jackets holds probably the best legacy , masculinity along with ruggedness to get a guys outer wear.

    ReplyDelete
  44. Well we really like to visit this site, many useful information we can get here.
    digital marketing courses in hyderabad with placement

    ReplyDelete
  45. Having come across this site, I believe I will learn something new and great from your article. Its nice read and my lovely time spent worthy it. Thanks for a wonderful updates. Click on.- fugashua post utme past questions pdf

    ReplyDelete
  46. Your work is very good and I appreciate you and hopping for some more informative posts
    data science training

    ReplyDelete
  47. Thanks for writing in with such positive feedback about my post. I took a quick glance at it and couldn’t stop reading!
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

    ReplyDelete
  48. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Motogp suits

    ReplyDelete
  49. Thank you for the information it helps me a lot we are lokking forward for more
    AI Training in Hyderabad

    ReplyDelete
  50. I am stunned by the information that you have on this blog. It shows how well you fathom this subject.
    data scientist certification malaysia

    ReplyDelete
  51. This comment has been removed by the author.

    ReplyDelete
  52. Nice post brother, I have been surfing online more than 3 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my view, if all web owners and bloggers made good content as you did, the internet will be much more useful than ever before. There is certainly a lot to know about this issue.I love all of the points you’ve made. I am sure this post has touched all the internet viewers.
    mua vé máy bay từ mỹ về việt nam hãng eva

    mua vé máy bay từ đức về việt nam

    giá vé máy bay từ anh về hà nội

    đưa công dân từ úc về việt nam

    Ve may bay Vietnam Airline tu Dai Loan ve Viet Nam

    vé máy bay từ vancouver về việt nam

    ReplyDelete
  53. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work
    data science training

    ReplyDelete
  54. I like your blog very much. Thanks for sharing such amazing blogs always.
    Yankees Blue Bomber Jacket

    ReplyDelete
  55. Good post. I would like to thank you for the effort you put into writing this interesting and informative article. If you need a visa to enter Turkey, you can apply for Turkish Visit Visa and Visa Application Form Can fill e Visa Turkey. It usually doesn't take too long to process and obtain a Turkey Electronic Visa

    ReplyDelete
  56. I Have Been wondering about this issue, so thanks for posting, please, what are the Ways on How to start a mortgage brokerage business anywhere in the world? thanks.

    ReplyDelete
  57. POKERBET88 merupakan salah satu situs permainan kartu Online terbaik, aman dan terpercaya dengan persentase kemenangan yang tinggi saat ini di Indonesia. Situs ini juga menyediakan berbagai macam permainan poker Online uang asli yang populer dengan sistem dan server stabil yang mudah di akses serta bonus kemenangan ratusan juta rupiah setiap hari

    ReplyDelete
  58. I really like your effort it is very informative articles . Thanks for your efforts. Please check the Kenya visa application form. It is very simple and useful for people who like traveling to other countries .

    ReplyDelete
  59. A great website with interesting and unique material what else would you need.
    cyber security course in malaysia

    ReplyDelete
  60. This is a very useful article. type of Indian visas, Business, Tourist, conference, Employment, Project visa etc. You can read full info on the types of Indian visa and requirement of all visas via the Indian visa website.

    ReplyDelete
  61. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.
    full stack developer course

    ReplyDelete
  62. Interesting and attractive information. This blog is really rocking... Yes, the post is very interesting and I enjoy it a lot. How India Visa Works? In 3 simple steps you can get your visa. You can fill your online application form &, then upload all documents & pay your visa fee.

    ReplyDelete
  63. Естественные катаклизмы или церемониальные жертвоприношения с течением времени основали определенное интерпретацию увиденного. Первые средства гадания были образованы тысячи лет назад до нашей эры. Что обо мне думает загаданный мужчина гадание значится максимально точным действием просмотреть грядущее личности.

    ReplyDelete
  64. Shreeja Oil Maker is a global leading manufacturer, wholesaler, supplier, exporter of various small scale machinery. Shreeja oil maker machine or Mini Oil Maker Machine Manufacturer is one of our innovative product which is able to extract 100% pure oil from the various seed. This is also known as a cold oil press machine or mini oil Ghani. We have a stronghold in national as well as a worldwide market.

    ReplyDelete
  65. Hello guys, India visa from USA can be applied online via India e visa portal. And you can learn more info about Indian visas through our website.

    ReplyDelete
  66. prevail! it may be one of the most useful blogs we've ever come across upon the situation. terrific data! Im plus an skillful in this subject matter correspondingly i can take your effort completely dexterously. thanks for the large backing. Brothers Day Quotes

    ReplyDelete
  67. Hii sir, I love reading this post, I always appreciate topics like these that are being discussed with us. Great information. I will follow the post thanks for sharing. Travelers have a query about: how to apply for a visa to Turkey ? Now you can get a visa by 3 simple steps like filling an application form online, then making payment and receiving it in your email.

    ReplyDelete
  68. This comment has been removed by the author.

    ReplyDelete
  69. Your article is easy to read and understand. I would like to read more articles like this. Getting a Turkish e visa online is a hassle free process. It saves time and money as well.

    ReplyDelete
  70. Well written. I appreciate for efforts on blog. Grow your career in Java Course in Greater Noida which help, you in getting best knowledge.

    ReplyDelete
  71. I like the way you express information to us. Thanks for such post and please keep it up. Star Trek Picard Field Jacket

    ReplyDelete
  72. Unified communications and Ip Pbx includes the connection of various communication systems both for the collaboration tools as the digital workforce.

    ReplyDelete
  73. In my blog post, I delve into the complex terrain of profound comprehension, weaving words with finesse. Each section acts as a beacon, illuminating pathways through uncharted intellectual territories. With eloquence, I craft a narrative that envelops readers, transporting them on an enchanting voyage through deep concepts.

    ReplyDelete
  74. "Such an enriching piece! Your mastery over the subject shines brightly, guiding readers through a maze of information effortlessly. The clarity with which you present complex ideas is commendable, catering to a wide audience with varying levels of expertise. Additionally, your friendly demeanor makes the reading experience akin to a pleasant conversation. Eagerly anticipating future posts from you.

    ReplyDelete
  75. This post is a treasure trove! Your command over the topic is evident, leading readers on a captivating journey of discovery. The way you unravel intricate concepts is commendable, ensuring accessibility for all. Furthermore, your friendly tone fosters a sense of connection, making the reading experience both informative and enjoyable. Can't wait to delve into more of your insightful content.

    ReplyDelete
  76. This post on building custom XHTML5 tags is quite insightful, especially for those looking to customize their web development projects. Customization is key in many areas, whether it’s in coding or fashion. For instance, I've been exploring ways to personalize my wardrobe and found that Harley-Davidson leather jackets offer a great mix of classic style and rugged individuality. They’re perfect for anyone who appreciates high-quality craftsmanship and timeless design.

    ReplyDelete
  77. The best-in-class manufacturers of Wood Oil Ghani Machines, Cold Press Oil Machinery, and Wooden Mill Machinery which are extensively used for the production of Groundnut Oil, Flaxseed Oil, Sesame Oil, Castor Oil, Coconut Oil, Mustard Oil, and many more.

    ReplyDelete
  78. Looking to honor the brave while showing your Detroit Lions pride? Our Detroit Lions Salute To Service Camo 2024 Hoodie is the perfect way to do just that. Featuring a common design with a nod to those who serve, it's a bold choice for Lions fans this season.

    ReplyDelete