$(function() {
$('#data').on('click', function(e){
e.preventDefault();
$(this).data('hello', "yeah");
});
$('#data2').on('click', function(e){
e.preventDefault();
$(this).data('hello', "yeah", true);
});
$('#data3').on('click', function(e){
e.preventDefault();
$(this).data('hello', {}, true);
});
$('#data4').on('click', function(e){
e.preventDefault();
$(this).data('hello', 1, true);
});
$('#attr').on('click', function(e){
e.preventDefault();
$(this).attr('data-hello', "yeah");
});
$('#attr2').on('click', function(e){
e.preventDefault();
$(this).attr('data-hello', 1);
});
$('#prop').on('click', function(e){
e.preventDefault();
$(this).prop('data-hello', "yeah");
});
/*
// $.fn.data() uses $.fn.triggerHandler() so changeData won't bubble
// this actually makes sense for heavy .data() usage unrelated to the dom
$('#data').on('changeData', function(e, name, value) {
console.log(name, value, this);
$(this).attr(name, value)
});
*/
});
<h1>Selectable updates</h1>
<p>Click the following buttons to see if their respective jQuery call updates the element's data-attribute or not</p>
<h2>Not updating the attribute</h2>
<p>
<button id="data" type="button">$.data('hello', "yeah")</button>
<button id="prop" type="button">$.prop('data-hello', "yeah")</button>
</p>
<h2>Updating the attribute with value</h2>
<p>
<button id="data2" type="button">$.data('hello', "yeah", true)</button>
<button id="attr" type="button">$.attr('data-hello', "yeah")</button>
<button id="data4" type="button">$.data('hello', 1, true)</button>
<button id="attr2" type="button">$.attr('data-hello', 1)</button>
</p>
<h2>Updating the attribute with default value <code>~defined~</code></h2>
<p>
<button id="data3" type="button">$.data('hello', {}, true)</button>
</p>
/* 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;}
External resources loaded into this fiddle: