Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jQuery .data() does not render this plugin redundant! #2

Open
x3rAx opened this issue Jun 9, 2017 · 0 comments
Open

jQuery .data() does not render this plugin redundant! #2

x3rAx opened this issue Jun 9, 2017 · 0 comments

Comments

@x3rAx
Copy link

x3rAx commented Jun 9, 2017

In the README.md you state that jQuerys .data() method renders your plugin redundant. This is not the case as .data() will not access the data-attribute. Instead, jQuery has an internal data store that holds the "data" assigned to each DOM element.

For convenience jQuery will initially fill that data store with the values of the data-attributes when you first select it using jQuery.

That means, that you can't change the value of the data-attribute using .data(). You also will not receive any changes to the data attributes value using .data().

Example:

<div id="test" data-hello="world"></div>
var $test = $('#test');

// You can get the value of the data attribute using .data() after the element has
// been selected for the first time:
$test.data('hello');      //=> 'world'
$test.attr('data-hello'); //=> 'world'

Now lets change the data using .data():

// When you change the data using .data(), the attribute value won't change:
$test.data('hello', 'data');
$test.data('hello');      //=> 'data'
$test.attr('data-hello'); //=> 'world'
<div id="test" data-hello="world"></div>

As you can see, the attribute value has not changed. Now lets use .attr() to update the value of our data-attribute:

// Vice versa, changing the attribute value will not update the data value:
$test.attr('data-hello', 'attribute');
$test.data('hello');      //=> 'data'
$test.attr('data-hello'): //=> 'attribute'
<div id="test" data-hello="attribute"></div>

Now the attribute value has changed but .data() still returns 'data' rather than 'attribute'.

This is essential when you want to use the data-attribute with CSS:

<div id="my-elem" data-size="small">
    <!-- ... -->
</div>
[data-size="small"] {
    /* ... */
}

[data-size="large"] {
    /* ... */
}
$('#my-button').on('click', function() {
    var $myElem = $('#my-elem');

    $myElem.data('size', 'large');      // This will have no effect.
    $myElem.attr('data-size', 'large'): // Yep, that works.
    $myElem.dataAttr('size', 'large');  // Like a charm!
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant