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!

79 comments:

  1. Replies
    1. IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes. IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble.Final Year Projects for CSE

      Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining .

      Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

      The Angular Training covers a wide range of topics including Angular Directives, Angular Services, and Angular programmability.Angular Training

      Delete
  2. This is an awesome post. Really very informative and creative contents. This concept is a good way to enhance knowledge. I like it and help me to development very well. Thank you for this brief explanation and very nice information. Well, got good knowledge.
    WordPress development company in Chennai

    ReplyDelete
  3. 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
  4. 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
  5. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    msbi online training

    ReplyDelete
  6. 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
  7. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
    msbi online training

    ReplyDelete
  8. 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
  9. 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
  10. Thanks for sharing Great info… learning driving from experienced instructors help you to learn driving very fast. Driving School Melbourne

    ReplyDelete

  11. When you feel any kind of body pain, it is best if you go to the doctor for treating it. Sometimes body pain can be the symptom of some serious disease. Sometimes body pain attacks us suddenly because of which you may not able to get the help of the doctor. In those situations, to get quick and effective pain relief, you can take the help of painkillers though they cannot cure your pain. As your painkiller, choose Tramadol 50 mg which is very effective. This painkiller is available in the market with the name of Ultram. To use this painkiller, you can get it easily. Buy Tramadol online and get this painkiller at an affordable price.
    Buy Tramadol online

    ReplyDelete
  12. 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
  13. live draw hk banyak terdapat perbedaan dari situs2 penyedia live hk ini. Sedikit saran apabila anda setiap harinya mengikuti live draw hk kami pastikan selalu menggunakan situs live hk yang kami rekomendasikan saja. Termasuk juga untuk live draw sgp ataupun live sgp alternatif ini.

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

    ReplyDelete
  15. Poker online situs terbaik yang kini dapat dimainkan seperti Bandar Poker yang menyediakan beberapa situs lainnya seperti http://62.171.128.49/hondaqq/ , kemudian http://62.171.128.49/gesitqq/, http://62.171.128.49/gelangqq/, dan http://62.171.128.49/seniqq. yang paling akhir yaitu http://62.171.128.49/pokerwalet/. Jangan lupa mendaftar di panenqq

    ReplyDelete

  16. 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
  17. After I initially commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on each time a comment is added information I receive 4 emails with the same comment. There has to be a means you can remove me from that service? Thanks a lot!

    ReplyDelete
  18. 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
  19. Great technology web site you have got here.. It’s hard to find quality writing like yours these days. I really appreciate individuals like you! Take care!!

    ReplyDelete
  20. 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
  21. This creative article has widened my knowledge . The brief explanation of this blog helps me to move further to the next level in this subject matter. Thanks for sharing this blog. Web Designing Course Training in Chennai | Web Designing Course Training in annanagar | Web Designing Course Training in omr | Web Designing Course Training in porur | Web Designing Course Training in tambaram | Web Designing Course Training in velachery

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

    ReplyDelete
  23. Nice article very helpful and informative thanks for sharing this information Full post
    Jio Missed call alert

    ReplyDelete
  24. 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
  25. 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
  26. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me.

    Microsoft Online Training

    Microsoft Classes Online

    Microsoft Training Online

    Online Microsoft Course

    Microsoft Course Online

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

    ReplyDelete
  28. The great website and information shared are also very appreciable.
    terror billy jacket

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

  30. Wow. That is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious.I want to refer about the best msbi training in bangalore

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

    typeerror nonetype object is not subscriptable

    ReplyDelete
  32. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    tibco sportfire online training
    best tibco sportfire online training
    top tibco sportfire online training

    ReplyDelete
  33. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    tibco sportfire online training
    best tibco sportfire online training
    top tibco sportfire online training

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

    ReplyDelete


  35. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.I want to share about tibco training .

    ReplyDelete
  36. Top quality blog with very informative information found very useful thanks for sharing.
    Data Analytics Course Online

    ReplyDelete
  37. Our the purpose is to share the reviews about the latest Jackets,Coats and Vests also share the related Movies,Gaming, Casual,Faux Leather and Leather materials available Billy Butcher Coat

    ReplyDelete
  38. Nice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
    Cyber Security Course in Bangalore

    ReplyDelete
  39. Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
    Cyber Security Training in Bangalore

    ReplyDelete
  40. 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
  41. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    best tibco sportfire online training

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

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

    ReplyDelete
  44. Thank you so much for shearing this type of post.
    This is very much helpful for me. Keep up for this type of good post.
    please visit us below
    data science training

    ReplyDelete
  45. Nice Blog !
    Here We are Specialist in Manufacturing of Movies, Gaming, Casual, Faux Leather Jackets, Coats And Vests See Hughie Campbell Jacket

    ReplyDelete