I see a lot of Html tags these days with attributes that start with data- as in the following example.
<button type="button" class="btn" data-dismiss="modal" aria-hidden="true" ng-click="closeClippingModal();">Cancel</button>
My question is simply this. Why is this used?
It is an html5 attribute meant to store things like meta data or other data associated with the element. It's commonly used to store state in JavaScript applications.
You can easily access it using JQuery like so $("#myElement").data("dismiss");
Most common use is storing data for javascript. As an example lets say you have a photo and you want to display it on webpage with hover efect being location and time of image taken. The simpliest way of storing data asociated with element is to use data-* attribute on the element:
<img src="my/awesome/photo.jpg" data-location="Paris, France" data-datetime="30.3.2014 16:19:00" />
It's as simple as that.
The data-* attributes is used to store custom data private to the page or application, 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).
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.
This feature is described quite well in John Resig’s blog.
Simply, the specification for custom data attributes states that any
attribute that starts with “data-” will be treated as a storage area
for private data (private in the sense that the end user can’t see it
– it doesn’t affect layout or presentation).
This allows you to write valid HTML markup (passing an HTML 5
validator) while, simultaneously, embedding data within your page
One of reasons is storing data instead of class. This is more semantic way. Data-attributes is the HTML5 novation. Also you can easily access them through JS (dataset) and jQuery (data() method). For more information see the specification: http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes
The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"
As I know data-attribut's name can contain uppercase letters but these letters will be forcibly converted in lowercase.
Related
I have a doubt about good practices writing HTML with Javascript.
I've came up with an idea (probably not the first, but couldn't find a clear reference about that) to mark some elements as candidates to load some data when it's available (after some user interaction). Let me exemplify:
Suppose I have a request that returns the following:
GET /animals/dog
{
name: "Gutemberg",
race: "doberman",
age: "2y"
}
The code I wrote binds fields in the response to elements that are candidates to load such value.
For example: With the request above, I could use the following tags:
<input name="dog-name-field" data-load-dog-name type="text"/>
<input name="dog-age-hid" data-load-dog-age type="hidden"/>
Each tag would receive the property value because it's marked as a candidate to do so - dog-name-field will have a value of "Gutemberg" when everything executes . That will happen everytime the request is reloaded. For now, I just get the data type I've searched ("dog"), concat it with the property "name/age" to form the attribute data-load-type-property and set a value to everyone that has such attribute.
I have a feeling that attributes are not meant to be used just like that, but I'm not aware of any real downsides to that. As I could not find it for the lack of a clear name to this approach, I'd like some guidance.
Is there a name for such technique? Is it a bad practice? If so, why?
PS:
To comply with SO good practices, I'd like the answers to be reference-guided and not based solely on opinion whenever possible. If no reference is provided, please, let us have a solid, well described example.
I have a feeling that attributes are not meant to be used just like that
Let's see what custom data attributes are meant to be used for:
Custom data attributes are intended to store custom data private to
the page or application, for which there are no more appropriate
attributes or elements. These attributes are not intended for use by
software that is independent of the site that uses the attributes.
(from w3.org)
So whether using data-attributes is "appropriate" in your case depends on your needs: if the DOM API doesn't provide better attributes to do that then it's appropriate.
If your need is just to select some element to change the textContent then you have two more appropriate/simpler options:
1) Using the id attribute if your elements are going to be unique in the document
The id global attribute defines a unique identifier (ID) which must be
unique in the whole document. Its purpose is to identify the element
when linking (using a fragment identifier), scripting, or styling
(with CSS).
(from id on MDN)
2) Using the class attribute if your elements are going to be used in multiple instances in the document
The class global attribute is a space-separated list of the classes of
the element. Classes allows CSS and Javascript to select and access
specific elements via the class selectors or functions like the DOM
method document.getElementsByClassName.
(from class on MDN)
As #Supr says in his answer, what you are doing is a very simple implementation of data-binding. data-binding can involve a lot more complexity than what you are doing at the moment; for example you may want to:
keep in sync your UI with a Javascript object which represent your business model instead of directly injecting data coming from an Ajax call,
update other attributes (value, style) and not only innerHTML or textContent,
have your business model updated in reaction to changes on the UI (two way data binding)
To implement all these features, simple id and class selectors are not sufficient, and this is why frameworks which implement data-binding, like KnockoutJS or AngularJS, use the more flexible data-* attributes instead (AngularJS is actually using its own ng-* attributes, but allows to use the alternative data-ng-* syntax for using HTML validation tools).
Data attributes allow to describe much more complex bindings:
<input data-bind="visible: editing, value: name, hasFocus: editing" />
Check KnockoutJS documentation for the meaning of the above code, it is not relevant to this example but just imagine describing that with classes or ids, it wouldn't be very convenient.
TL;DR
If you don't plan to implement more complex features you might want to use class and id instead.
This is called binding. Sometimes data binding and sometimes template binding.
Various frameworks provide mechanisms for this, though the syntax varies.
AngularJS example:
<input ng-model="dog.name" />
Knockout example:
<input data-bind="textInput: dog.name" />
React example:
<input value={this.state.dog.name} />
These are all quite popular frameworks/libraries, so I think it's safe to say it is not considered bad practice. The main difference from your approach is that they use the value of the attribute to specify the reference into the model (i.e. the "dog.name" part of your attributes), while you are putting the reference in the attribute name. In practice this is mostly a matter of style. Separating the reference from the "marker" (i.e. "data-load") is perhaps a bit more readable.
I recently downloaded a code and it shows
<button data-effect="st-effect-4">Slide along</button>
From what I figured out "st-effect-4" is a class name but can anyone tell me what this data-effect is for?
HTML5 allows for custom attributes, as long as they begin with "data-". This is a custom attribute with a specific value.
Those are called HTML5 Custom Data attributes.
Custom data attributes are intended to store custom data private to
the page or application, for which there are no more appropriate
attributes or elements. These attributes are not intended for use by
software that is independent of the site that uses the attributes.
Every HTML element may have any number of custom data attributes
specified, with any value.
The reason why you can't find it in Google is because those attribute are custom attributes generated by user for there own use.
It's not for anything.
HTML5 specifies that (just about) any element can have any "data-*" attributes it wants, which can hold any values they want (as long as they can be treated like strings, to store on the element).
So that might be part of a library, or it might just be somebody's CSS for a selector like:
button[data-effect] { background : blue; }
button[data-effect="st-effect-4"]:active { background : purple; }
Or it's being used as a query selector, in JS, for a game's controls...
Who knows?
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
These attributes are not intended for use by software that is independent of the site that uses the attributes.
Every HTML element may have any number of custom data attributes specified, with any value.
For Mary Lou's tutorial - this is to control the animation that brings in the menu.
This can be re-assigned to other trigger elements - however the code that makes it live is the DIV element that comes just before - st-trigger-effects.
If you look through the code and the CSS that controls it, you will be able to re-assign that to where-ever you need to use it.
I am currently using this in a bootstrap boilerplate for a University project.
src: http://tympanus.net/codrops/2013/08/28/transitions-for-off-canvas-navigations/
I've faced two strange attributes of an html tag . They are "data-url" and "data-key".
What are they and how can they be used?
For some reasons i can't show the exact example of the HTML file I've found them in, but here are some examples from the web with such tags:
data-key
data-key
data-url
PS: I've tried to Google, but no useful results were found.
When Should I Use the Data Attribute?
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
This time the data attribute is used to indicate the bubble value of the notification bubble.
Profile
This time is used to show the text for the tooltip.
This is the link
When Shouldn’t I Use the Data Attribute?
We shouldn’t use data attributes for anything which already has an already established or more appropriate attribute. For example it would be inappropriate to use:
<span data-time="20:00">8pm<span>
when we could use the already defined datetime attribute within a time element like below:
<time datetime="20:00">8pm</time>
Using Data Attributes With CSS (Attribute selectors)
[data-role="page"] {
/* Styles */
}
Using Data Attributes With jQuery (.attr())
Google
$('.button').click(function(e) {
e.preventDefault();
thisdata = $(this).attr('data-info');
console.log(thisdata);
});
Examples and info from here
Those are called HTML5 Custom Data attributes.
Custom data attributes are intended to store custom data private to
the page or application, for which there are no more appropriate
attributes or elements. These attributes are not intended for use by
software that is independent of the site that uses the attributes.
Every HTML element may have any number of custom data attributes
specified, with any value.
The reason why you can't find it in Google is because those attribute are custom attributes generated by user for their own usage.
From seeing your code it seems:
The person who has written this code, wants to store some additional
information with the elements. Not sure he may handle this in
Javascript too.
What you should do is to check the Javascript code completely,
whether he is handling those data attributes or if possible check
with him.
Since you code is using jQuery library, check for .data()
method. After a complete code review, if you find it has no use,
then feel free to remove.
data-* attributes are for adding arbitrary data to an element for use solely by the code (usually client side JavaScript) running on the site hosting the HTML.
In order to tell what the three examples you give are for, we would have to reverse engineer the code that comes with them (unless they are documented on the sites) since they don't have standard meanings.
A new feature being introduced in HTML 5 is the addition of custom data attributes. Simply, the specification for custom data attributes states that any attribute that starts with “data-” will be treated as a storage area for private data (private in the sense that the end user can’t see it – it doesn’t affect layout or presentation). This allows you to write valid HTML markup (passing an HTML 5 validator) while, simultaneously, embedding data within your page. A quick example:
<li class="user" data-name="John Resig" data-city="Boston"
data-lang="js" data-food="Bacon">
<b>John says:</b> <span>Hello, how are you?</span>
</li>
I need to verify using Selenium (or similar framework) that certain HTML content/items are on the page using known unique identifiers.
I have control over the generation of the HTML, so I will mark the HTML tags with an attribute, but sometimes the usual candidates of id, name etc aren't available for me to use.
Is there an industry standard for such an attribute?
If not, anyone have any good suggestions?
The attribute shouldn't collide with any known attributes of any HTML elements or affect the web experience/behaviour (I don't care if someone reads the HTML source and sees it).
Some ideas I have are:
trace
debug
uid
Here's how I would like to use it for the example identifier "123456789":
<a trace="123456789" href="http://www.someurl.com">Click me!</a>
<span debug="123456789">Hello world</span>
<strong uid="123456789">Wow</strong>
Use a HTML5 data-* attribute.
Custom data attributes are intended to store custom data private to
the page or application, for which there are no more appropriate
attributes or elements.
More information here: http://developers.whatwg.org/elements.html#embedding-custom-non-visible-data-with-the-data-*-attributes
They won't cause any problems in older browsers: http://caniuse.com/dataset
I've noticed a lot of websites with form(s) containing input fields whose "name" attribute is specified even if it isn't used for styling or scripting purpose!
Moreover, according to the official document about the form in HTML document ...
name = cdata [CI] This attribute names
the element so that it may be referred
to from style sheets or scripts. Note.
This attribute has been included for
backwards compatibility. Applications
should use the id attribute to
identify elements.
So, my question is: should this attribute used only for styling and scripting purposes?
Thanks in advance!
EDIT: In particular, could be avoided the use of this attribute with input fields of "text" type (when there aren't no styling or scripting purposes)?
EDIT 2: So, you have almost confirmed what I had thought about: the "name" attribute will be deprecated in further HTML specifications/standards!!!??? It is still "alive" only for backwards compatibility ... in some cases can be avoided but there are still some cases (such as the radio button) where it is necessary!
I think you'll find almost every site will have inputs with the name attribute. I don't see it going away anytime soon.
The name attribute specifies a name
for an input element.
The name attribute is used to identify
form data after it has been submitted
to the server, or to reference form
data using JavaScript on the client
side.
Note: Only form elements with a name
attribute will have their values
passed when submitting a form.
source
The name attribute is the notation to reference specific elements within the scope of a webpage through non-DOM Javascript:
document.forms['your_form'].elements['aa']
The id attribute for the element needs to be set with the same value for the following to work:
document.getElementById('aa')
My understanding is that when Netscape created Javascript, it used the name attribute. The HTML spec however decided to go with id, but kept name for backwards compatibility. IME, using the name attribute was required for Internet Explorer 6 support because the javascript engine in IE wouldn't read the id attribute - only the name though both were defined.
...could be avoided the use of this attribute with input fields of "text" type (when there aren't no styling or scripting purposes)?
If you don't have any javascript attached to the text fields, yes - they would be unnecessary.
There are differences between id and name attributes. An id is applicable to any element in the HTML document while a name is relevant for input fields only. An id is required by standard to be unique in a page (though not necessarily followed in all web pages). Different elements may have same name though. One particular case comes into mind is the radio button. All radio buttons should have the same name and the value of the one selected would be given back to the form. So you can see that name still has significance in HTML form processing.
I have seen in automatic HTML form generation systems (like zope.formlib), that id and name attributes both are automatically generated for different types of input widgets. Such automatic form generation systems take proper care of all the nuances associated with differences in id and name attributes. They also do things like generating a hidden input element for each checkbox element. So wherever possible, I try to use some sort of automatic HTML form generation mechanism and let it take care of the issues involved.
This is an old question, but it's worth noting that many modern JS frameworks rely on the name attribute. In particular, jQuery's serialize function:
For a form element's value to be included in the serialized string, the element must have a name attribute.
If anything, name seems to be making a comeback.
It's also worth noting that the name attribute is useful because it has slightly more "scope" than id. id must be unique within a page, but the same name can be used multiple times. This makes it useful when you have multiple forms on the same page, or when you want to reference a group of checkboxes, etc.
IIRC older browsers use name in place of ID, that's why it's normally included.
Your reference to HTML 4 is way out of date. Here's WHATWG's discussion of name - https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#naming-form-controls:-the-name-attribute
name should not be used for scripting or styling. That is what id is for as you have said.
But name is not obsolete and I see no prospect that it might be removed from HTML. Its purpose is specifically to submit data to a server.
id should be unique for your HTML document to be well formed. name might not be. You might have a set of three radio buttons, let's say "Small", "Medium" and "Large". You could give them three unique values for their id attributes, so if your user interacts with other elements you could change the selected radio button in script. But when the form is submitted, you want only one value to be submitted, so you give all three radio buttons the name value for name.
<input type="radio" id="size-small" name="size">Small</input>
<input type="radio" id="size-medium" name="size">Medium</input>
<input type="radio" id="size-large" name="size">Large</input>