JavaScript Triggers

by Peter-Paul Koch

140 Reader Comments

Back to the Article
  1. Peter Paul Koch is not writing here something interesting that has news value.

    In fact he keeps rewriting his more than one and half year old writing

    Forms, usability, and the W3C DOM : Comments
    By Peter-Paul Koch
    Published on May 30, 2003
    http://digital-web.com/articles/forms_usability_and_the_w3c_dom/comments/

    and sells this for newbees as a new article and as seen here very many praise him.
    He just has added doubtful paragraph about custom DTDs and thats pretty much it.

    Copy & paste the code below to embed this comment.
  2. Matching a class name in JavaScript can be tricky, especially if you want to be able to apply more than one class to an element and still not match trick classes (like on the last list item).
    In this example we’re looking for an expression that matches the first four items in the list.
    Note that the last method is the correct approach, the first two are wrong.

    <ul>
    <li class=“two”>Crocodile</li>
    <li class=“one two”>Beaver</li>
    <li class=“two three”>Pig</li>
    <li class=“one two three”>Monkey</li>
    <li class=“one-two-three”>Horse</li>
    </ul>


    Following two methods will not work.

    if (element.className == “two”) {
    // Matches first list item only
    }

    if (element.className.indexOf(“two”) != -1) {
    // Matches all list items
    }


    This one however will.

    if (element.className.match(/( |^)(two)( |$)/)) {
    // Matches first four list items
    }

    Copy & paste the code below to embed this comment.
  3. var temp = element.classname.split(” “);

    for(i=0; i<temp.length; i++)
    {
    // now match with == or use switch/case
    // and all is well
    }

    Copy & paste the code below to embed this comment.
  4. Inspired by PPK’s article, I revised the forms for the Drink-Drive-Lose Ad Challenge: http://www.drink-drive-lose.com/adchallenge/notify.php

    Copy & paste the code below to embed this comment.
  5. Marek Mänd is not writing here something interesting that has news value.

    In fact he has written absolutely nothing that has any value whatsoever.

    And sells this for newbees as a viable critique of an article he couldn’t have written himself.

    He just has established beyond doubt that he’s jealous and thats pretty much it.

    Copy & paste the code below to embed this comment.
  6. Oops. I fell for the Capital letter meme.

    PPK’s method is just one method. We can rule out behaviours because:
    1. They don’t validate
    2. They are browser proprietary

    Admitted, PPK’s method fails #1 too but it does pass #2. Like it or not I still say that a custom attribute is the most semantically correct way.

    Copy & paste the code below to embed this comment.
  7. As Adrian and Dave pointed out, the ability to use the class attribute for things other than CSS classes is allowed. I’m not sure I follow the idea that this doesn’t allow us to keep the seperation between structure, presentation and behaviour, as the class attribute is already used to “bind” presentation to a structural element, why is this very same technique frowned upon for behaviour?

    Would Peter-Paul feel that having an attribute labelled “behaviour” with the ability to specificy function/object names better suited? Because this is essentially what the classnames are doing, only for presentation.

    The argument that mixing behaviour in with class names doesn’t allow for a clean seperation between structure and behaviour doesn’t really hold water with me, as this is exactly the same technique that is used to associate presentation with structure.

    However, I DO see a need to maybe seperate behaviour assignments from presentation assignments: this will lead to confusion (although were quite fortunate that this wont lead to a problem similar to what namespaces hope to clear up, as a classname could contain a behaviour called “button” and a CSS class called “button”)

    Anyways, fantastic article: some real food for thought there. Keep it up! I look forward to more articles from this author!

    Ben

    Copy & paste the code below to embed this comment.
  8. First off, great set of articles :-)

    In the entire class vs attribute discussion I personally think that it’s more logical to use the class. It’s just a matter of “abstracting” the behaviour in the same way as we now abstract the presetation through the CSS. To me, writing maxlength=“300” is about the same as writing a .red, .blew, .green, etcetera CSS class and applying them at random.

    I think that you need to separate the behaviour based on “what it is”, not on “what it should do”, exactly like we define CSS based on “what it is” (i.e. header) and not “what it should look like” (i.e. red, center). The most appropriate solution to me would be to simply have a <textarea class=“message”> and then define somewhere else how a messae textbox looks (CSS) and how it should behave (JS).

    This means that in my mind, values such as the maxlength should be put in the JS script or in a separate file/definition the JS reads from, and not in the (X)HTML markup.

    Copy & paste the code below to embed this comment.
  9. I’ve marvelled at many of the articles at ALA, and I agree it’s up to any individual designer to press the limits. My only annnoyance here is that ALA has been a champion of ‘standards’ yet when I follow the link to the quirksmode site, it doesn’t recognise firefox, and so I have to view a java-free version of the site. Not standards friendly – from the start. Then, on the browser page, no mention of firefox? What of these 25 million new users? I have no doubt that quirks’ owner is a brilliant programmer/designer etc etc, but this is not doing std comp any favours. Love tips/tricks etc, but in the scheme of things, this article is not much better than an article on some MS proprietory easter eggery – until “standards” catch up. Is ALA now hoping to do what MS did and champion buggy and restrictive, limited access techniques for delivering ‘cool’ content to those who are dumb enough (in a bug infested world) to enable java everything – for the sake of viewing ‘cool’ sites. Btw, I not only had to view an ugly “quirks.. site doesn’t support your browser” 404 style page, but it didn’t even auto-redirect. Not a good look. In ALA’s best defence, this is the first article where I feel ALA may have ‘jumped the shark’. (jump the shark: episode of Happy Days where Fonzy goes to Florida and daredevil style, ski-jumps over a killer shark – 2 part episode.. ratings fell immediately. Keep it real. This article can only add fuel to the fire that is the argument that: code-freaks will always find a way to break things and in doing so, make arguments for MS to fix us up.

    Copy & paste the code below to embed this comment.
  10. A Soul asked:

    >Is ALA now hoping to do what MS did and champion buggy and restrictive, limited access techniques for delivering ‘cool’ content to those who are dumb enough (in a bug infested world) to enable java everything – for the sake of viewing ‘cool’ sites.

    No.

    Copy & paste the code below to embed this comment.
  11. For certain behaviors, I’ve used this technique.  I also like it for validation triggered as you go (via onchange) rather than onsubmit.

    But for validation triggered from onsubmit, it doesn’t scale and I don’t like how I’m forced to maintain it.  After a form gets sufficiently complex, putting the validation parameters within each element becomes difficult to manage and support.  It is much easier, in my experience, to clump all of your validation code together within a single function, even if it means that removing a field now means to have to do it twice (once in the HTML, once in the validation script).  This becomes even more important when you have interconditional validation such as “If Status is not draft and Time_Sensitive is checked then make sure the estimated date is populated, valid, and, if marked as high priority, also within the next two weeks.”

    I’ve finally settled on a standard validation script library ( http://www.openntf.org/Projects/codebin/codebin.nsf/CodeBySubContributor/6B4512863D22FC9288256BF900521391 ) and love it (except that I’ve yet to get around to integrating overlib instead of an ugly alert box).

    By the way, a related link you might find interesting mixing presentation with validation by changing the css class name from “RequiredField” to “ValidField” in the onchange:  http://codestore.net/store.nsf/unid/DOMM-4RZH6P?OpenDocument Mixing that idea with this article would have some potential.

    Copy & paste the code below to embed this comment.
  12. >yet when I follow the link to the quirksmode
    >site, it doesn’t recognise firefox,

    Why should it have to recognize Firefox? Any site should work in any browser (and mine does).

    >and so I have to view a java-free version of >the site.

    My site is guaranteed 100% Java free because I don’t have the faintest idea how to write Java. Therefore every visitor sees the Java-free version.

    JavaScript is another matter, of course. If your browser doesn’t support the W3C DOM it doesn’t get the JavaScript interface.

    >Then, on the browser page, no mention of >firefox?  What of these 25 million new users?

    It mentions Firefox’s parent browser rather a lot, and with lots of details. You do need to know just the tiniest bit about browsers, though.

    >I not only had to view an ugly “quirks..site
    >doesn’t support your browser” 404 style page,

    That’s not what the page says. Please read again.

    >but it didn’t even auto-redirect.

    Where should it redirect to? Isn’t it better to give the visitor a choice of destinations?

    Copy & paste the code below to embed this comment.
  13. >but it didn’t even auto-redirect.

    Good response PPK. Excuse my overuse of metaphors, but redirecting someone in a situation like that would be the equivalent of you driving someone out to the middle of nowhere when they asked you for directions.

    I had a thought about getting around the whole validation problem thing. The only solution to use custom attribues WITHOUT any sort of DTD and to have the page validate is, well, there is none. It’s called a “tradeoff”. We have a lot of them (fixed vs fluid-width, text/html vs application/xhtml+xml, etc). I’m suprised so many developers aren’t used to them by now.

    Copy & paste the code below to embed this comment.
  14. For what it’s worth, to you probably not a lot, but to my clients a good chunk of change :), I thought I’d add my thoughts.

    To start with let me thank PPK and all of you who have taken the time to contribute to this discussion.  Not only has this article and comments been informative, but genuinely entertaining to think about.  It’s these kinds of issues that make web design and development so interesting to me.

    Let me also say that, like many developers, I strive for standards compliant design and development, but occasionally make non-compliant choices (or I should say compliance with older standards) brought on by the reality of today’s browsers.  Even the great Eric Meyers, CSS guru, uses a table for the basic layout of his examples in his books. gasp  However he strives for CSS usage in all other ways.

    So I’ve decided on the following path for myself:

    1. I’m going to add one additional attribute to my HTML elements, behavior.  I think this will add the least and get me the most.

    2. I’m going to keep my values for this attribute as simple as possible.  This is how I make my values for the class attribute.

    3. I think I need different “groupings” for presentational and behavioral.  For example, I want to display form elements in a single form in a consistent manner, but I want to validate email addresses in forms in a consistent way across pages in an application.  I think the combination of IDs, classes, and “behaviors” will give me all the hooks I need to handle the situations I’ve seen presented here and reduce redundancy in my code.

    4. I think this will keep my JavaScript as simple, clean and atomic as possible.

    5. I don’t have a problem with a custom DTD.

    6. I want to keep the details of my behaviors external to my structure.  For me I’ve decided to keep these details in my JavaScript file.  The reason I went with this as opposed to external XML files, etc, is again to keep my JavaScript and other code as simple as possible.

    So there it is.  My “centrist?” view of the ideas presented here.

    Thanks again for providing a space for and participating in this discussion.  It’s been very useful for me.

    JD

    Copy & paste the code below to embed this comment.
  15. Very often I find myself using a class I’ve written in PHP to generate forms dynamically, by which I mean, you can generate the forms from any database table without prior knowledge of what the table structure is. It is aware of the field lengths in the database and so for input elements it can dynamically include the maxlength attribute.

    For me this answers the question of whether maxlength information should be considered structural or behavioural: it just doesn’t matter. There just is no other good place to put the information except in the XHTML file when it is generated, either using element attributes or (as someone else suggested) inside a comment near the element.

    I have no problem thinking that the requirements of form fields are structural. What you end up doing when a user breaks the constraints is behavioural. In fact I’d go so far as to say that the choice bewteen textarea and input is more presentational than structural, whereas the validation requirements of the field are more structural than behavioural. The lack of maxlength attribute for textareas is an oversight. But that’s just my take.

    Copy & paste the code below to embed this comment.
  16. I love the idea of using custom attributes.  I’ve used classes to achieve this sort of thing in the past, and like the idea of using attributes for this purpose.

    The only thing I might add is the use of namespaces to use attributes within my own namespace.  For example js:required as opposed to just required.  This would clearly call out that the attribute isn’t defined by XHTML, rather some names space called js.  Namespaces in XML is a w3c standard: http://www.w3.org/TR/REC-xml-names/

    Copy & paste the code below to embed this comment.
  17. secured to the referenced articles of exploring those greetings off records,why break point?Systematically my motives toward
    further highlights to my 1st read indicates it
    is coming a-long.Now a natural formatt direct-
    ed already impedes as interluctory attributes
    however what does this mean?Structured analysis impliments my hope to those compiled
    referenced directions.My 1st DTD.reciped add
    xhtml,fol.by an ia},nobones;ah you already have my formula,I’ll consolidate when noid +
    sign is.RF><LF,turn and attribute live.Romnoid

    Copy & paste the code below to embed this comment.
  18. Why not just perform a match on the Name of the text field?  For instance, I use an onload=init() for the body that searches through all of the input tags that are type=text and adds onblur=validateDate(this) if the name of the text field contains ‘Date’.  I do something similar for ‘Phone’ and pretty much anything else I need to validate.

    I can also use the same code to add any number of classes to any or all of the text fields.  That way all the structure has to have is “<input type=text name=xyzDate>” and onload javascript attaches both presentation AND behavior so changing either requires absolutely NO changes to the structure.

    Copy & paste the code below to embed this comment.
  19. I’ve been following this debate (and the larger debate on alistapart.com) over structure vs. presentation.

    I have to say that part of me that wants things to be logical and efficient leans toward defining my web pages semantically, and then using CSS to control layout and design.

    However, the realist in me knows that this is a practical impossibility. Anyone that has designed a slightly complex website – especially one that involves variable formatting between pages – knows that writing perfectly semantically driven code is impossible. We always end up making little compromises to get our layout to work right. stuff like <div class=“clear”></div>
    is not semantic – but sometimes its the only way to deal with floated columns. Look at the code for this website – try and argue that its semantic not presentational! If alistapart.com, a magazine which is dealing with very spefic and predicable data chunks and consistent presentation, can’t write semanic code who can?

    The funniest thing is that we can kill ourselves designing these perfectly defined documents, but don’t all websites designed this way tend to end up looking very similar? Why? because if we design our documents semantically we lose a lot of layout flexibility. We can use CSS to achieve complex designs that look even better than table based designs – but websites designed this way are never defined semantically – and never will be, because at the end of the day, web pages are presentational documents. We don’t see similar arguments in the print layout community for semantically designed documents – so why in the web design community?

    I think the larger debate is an interesting one, but that in truth it applies to only a small subset of website applications, such as content management systems; and that even within this small subset of applications there is a lot or room for flexibility in how one strikes a balance between semantic logic and presentational necessitates.

    For MOST websites, none of this should be a concern. We can argue all we want if maxlength=200 is presentational or structural, and those people that design websites with the maxlength=200 hidden somewhere deep in the JavaScript because they have a firmly rooted ideological belief that it is structural not presentational – bring me a website that has no <div class=”clearboths”><div>’s I’ll be very impressed – but more surprised.

    Copy & paste the code below to embed this comment.
  20. Justin, your point is well made and quite on target, however, it is possible to make completely semantic sites and then, via JavaScript, add not only the behaviours, but also any “presentational” elements such as the divs you mentioned.

    Copy & paste the code below to embed this comment.