mathiasbynens / mathiasbynens/jquery-custom-data-attributes
jQuery .data() does not render this plugin redundant!
- Dominant language
- JavaScript
- Stars
- 20
- Forks
- 4
- PR merge metrics
- No merged PRs in 30d
Description
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:
```html
```
```javascript
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():
```javascript
// 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'
```
```html
```
As you can see, the attribute value has not changed. Now lets use .attr() to update the value of our data-attribute:
```javascript
// 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'
```
```html
```
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:
```html
```
```css
[data-size="small"] {
/* ... */
}
[data-size="large"] {
/* ... */
}
```
```javascript
$('#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!
});
```
Contributor guide
No contributing guide indexed for this repository
Research direction
Start in README.md and compare the statement about jQuery's .data() method with the issue's examples of .data(), .attr(), CSS selectors, and dataAttr(). Done means the README no longer says the plugin is redundant and accurately explains the difference between jQuery's data store and data-* attributes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, jquery
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 48/100