w3c html5 data- attributes fix for jquery

make a w3c compliant data-attribute from string

by thegrandoverseer

HTML

<fieldset>
    <legend>Translate data- attribute string to w3c specification</legend>
    <label for="dataattr">Data attribute string:</label>
    <input type="text" name="dataattr" id="dataattr" value="data-some-keyNameWIthDashesAndCamelCase" />
    <button name="attsubmit" id="attsubmit" type="button">Translate</button>
</fieldset>
<div id="translation" data-foo-bar='fooBar' data-FooBarBaz='foobarbaz' data-fooBar-BazBo='foobarBazbo'>
    TRANSLATION HERE
</div>

CSS

html *, body { font-family: sans-serif; font-size: 12px; }
body { padding: 1em; }
label, legend { font-weight: bold; padding-right: 1em; }
input[type="text"] {width: 400px; padding: 0.25em; font-size: 80%; margin-right: 1em; }
#translation { border:1px solid black; padding: 1em; background-color: pink; }

JavaScript

function jqmajorver() {
    return (jQuery && $().jquery || 0).split('.')[1] || 0;
}

function w3cdatakey(string) {
    //transform data-attributes string like data-foo-bar to fooBar and ones like data-fooBar to foobar
    //to comply with w3c HTML5 data- attributes specification, and changes to the way
    //jQuery transforms data- attributes to camelcase and lowercase after version 1.6
    var fixdashes = (jqmajorver() >= 6 ? true : false);
    var newstring = '' + string; //copy of string
    if (newstring.substr(0, 5) == 'data-') {
        newstring = newstring.substr(5);
    } //trim off leading 'data-' if provided
    newstring = newstring.toLowerCase();
    if ( !! fixdashes && newstring.match('-')) {
        var parts = newstring.split('-'),
            tmpstr = '';
        $.each(parts, function(i, el) { //replace dashes and make letters to right of dashes capitals (camelcase)
            tmpstr += (i === 0 ? el : el.charAt(0).toUpperCase() + el.slice(1)); //capitalize if not first item
        });
        newstring = tmpstr;
    }
    return newstring;
}

$(document).ready(function() {

    $('#attsubmit').click(function(e) {
        e.preventDefault();
        var el = $('#dataattr'),
            vall = el.val(),
            res = $('#translation');
        res.text(w3cdatakey(vall));
    });
    //onDomReady, get some data from data attributes already set
    var trans = $('#translation'),
        datadebug = '#translation data debugging: ',
        keys = ['data-fooBar', 'data-foo-bar', 'FooBarBaz', 'data-fooBar-BazBo'];
    $.each(keys, function(ii, ell) {
        datadebug += ell + '[' + w3cdatakey(ell) + ']: ' + trans.data(w3cdatakey(ell)) + '; ';
    });
    trans.before(datadebug);

});