Search code examples
javascriptjqueryhtmlcustom-data-attributesinemacula

Classes vs data attribute, auto field initialiser


A Little Background

I have written a method in javascript/jQuery that loops through fields and sets them dependant on what they are i.e. dropdown, autocomplete, text etc...

The reason for this is that I have specifically styled inputs and textareas, and they must be initialised in javascript once the page has loaded. The method in this class loops through each field on the page and sets the events based on what it is.

At the moment I am detecting what each field is by giving the field container a class, jQuery reads this class and sets the field accordingly like so:

<div id="company-container" class="autocomplete autocomplete-215 form-sprite">
    <input type="text" class="field" name="company" id="company" autocomplete="off" maxlength="80" tabindex="1" />
    <div class="label overflow" id="company-label">Company</div>
    <div class="glow form-sprite" id="company-glow"></div>
    <ul class="subNav"></ul>
</div>

The jQuery looks something like this:

$(options.fields).each(function(){
    // Set the field events
    SineMacula.setBlur($(this));        
    SineMacula.setFocus($(this));
    SineMacula.toggleLabel($(this));
    // If the field is a drop down then set it
    if($(this).parent().hasClass('dropdown')){
        SineMacula.setDropdown($(this).parent());
    }
    // If the field is a checkbox then set it
    if($(this).parent().hasClass('checkbox')){
        SineMacula.setCheckbox($(this).parent());
    }
    // and so on ...
});

Most of the code above can be ignored, but it should give you an idea of what I am doing...

Question

I have recently noticed the HTML5 attribute data-*, where * can be anything. My question(s) are:

  1. Should I be using the HTML5 data-* attribute instead of classes?
  2. Are there better methods than either the data-* attribute or the classes?
  3. Although the data-* attribute is HTML5, is it compatible with early browsers as long as the correct DOCTYPE is defined?

Solution

    1. In this case it probably doesn't matter too much, since you're still using a valid attribute (rather than random custom attributes). If you feel that data-* attributes would be more semantic, then go for it.

    2. No, that is what the data-* attribute is designed for - storing arbitrary data on an element.

    3. Yes, it's compatible with all browsers. It will just be ignored by older browsers, but you will always be able to retreive its value with the getAttribute method.