Marcus
Marcus

Reputation: 53

Dont understand jQuery .attr() Parameter

$newUser.addClass(newTweet.user).attr('data-user', newTweet.user).text('@' + newTweet.user + ': ');
var user = $(this).data('user');

On line 1 newTweet is an object, but I don't understand the parameter 'data-user. This isn't referenced in any of the other files, user, so is the 'data-' prefix performing some action? Or does it somehow reference line 2? Or am I completely wrong in both situations, I also don't understand how .addClass() method is working in this situation. How does a property of an object get added as a class?

Upvotes: 0

Views: 134

Answers (1)

SebastiaanYN
SebastiaanYN

Reputation: 636

The .attr() function adds an attribute to an element. You can read more about it here: http://api.jquery.com/attr/.

data-user is the name of the attribute added to the element. It doesn't provide any actions, but it's used to store data.

The data-* attributes is used to store custom data private to the page or application.

The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.

The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

The data-* attributes consist of two parts:

The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-" The attribute value can be any string

Note: Custom attributes prefixed with "data-" will be completely ignored by the user agent.

https://www.w3schools.com/tags/att_global_data.asp.

Both for the .attr() call and .addClass() it uses the value of newTweet.user, which might be a string.

Upvotes: 2

Related Questions