jQuery.dataAttr()
using jQuery.data() so it's selectable by CSS
by rodneyrehm
HTML
<h1>Selectable updates</h1>
<p>
<button id="data" type="button">$.dataAttr('hello', "yeah")</button>
<button id="data2" type="button">$.dataAttr('hello', 1)</button>
<button id="data3" type="button">$.dataAttr('hello', {foo: true})</button>
</p>
CSS
/* set background for elements with "data-hello" attribute */
[data-hello] { background-color: blue; }
[data-hello="yeah"] { background-color: green; }
[data-hello="1"] { background-color: orange; }
h1 {font-size: 1.2em; font-weight: bold; margin: 5px 0;}
h2 {font-size: 1.1em; font-weight: bold; margin: 15px 0 5px 0;}
JavaScript
(function($, undefined) {
if (!$.uncamelCase) {
// Convert camelCase to dashed
$.uncamelCase = function(string) {
return string.replace( /([A-Z])/g, '-$1' )
.toLowerCase().replace( /^-/, '');
};
}
// dispatch to data() and attr()
$.fn.dataAttr = function(key, value) {
var $this = this,
ret = this.data(key, value);
if (typeof key == "object") {
$.each(key, function(key, value) {
$this.attr("data-" + jQuery.uncamelCase(key), typeof value in {string:1, number:1} ? value : '~defined~');
});
} else if (value !== undefined) {
$this.attr("data-" + jQuery.uncamelCase(key), typeof value in {string:1, number:1} ? value : '~defined~');
}
return ret;
};
$(function() {
$('#data').on('click', function(e){
e.preventDefault();
$(this).dataAttr('hello', "yeah");
});
$('#data2').on('click', function(e){
e.preventDefault();
$(this).dataAttr('hello', 1);
});
$('#data3').on('click', function(e){
e.preventDefault();
$(this).dataAttr('hello', {foo: true});
});
});
})(jQuery);