- Working with HTML5 data attributes
- How do data attributes work? #
- What can you store? #
- Reading/writing data attributes with JavaScript #
- Reading/writing data attributes with jQuery #
- Using the dataset API #
- Things you can do with data attributes #
- Filtering #
- Styling #
- Configuring #
- A better way to store data #
- HTML Web Storage API
- Browser Support
- HTML Web Storage Objects
- The localStorage Object
- Example
- Example
- The sessionStorage Object
- Example
- How to store and use data in HTML
- Data Block
- Data Scheme
- Data Attribute
- Json Module
- HTML5 Web Storage
- What is Web Storage?
- The localStorage Object
- Example
- Example explained:
- The sessionStorage Object
- Example
Working with HTML5 data attributes
Heads up! This post was written in 2014, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you’re reading.
Before HTML5, working with arbitrary data sucked. To keep things valid, you had to stuff things into rel or class attributes. Some developers even created their own custom attributes. Boy, was it a mess.
But that all changed with the introduction of HTML5 custom data attributes. Now you can store arbitrary data in an easy, standards-compliant way.
How do data attributes work? #
A data attribute is exactly that: a custom attribute that stores data. They are always prefixed with data- followed by something descriptive (according to the spec, only lower case letters and hyphens are allowed). An element can have any number of data attributes you want.
Here’s an example using a list item to store data for a user:
Of course, this data isn’t very useful to a visitor because they can’t actually see it, but it’s wildly useful for building web applications. Imagine a delete button in your app:
All the data you need is right there to send to your backend script. No more rel stuffing or parsing IDs and actions out of other attributes. Data URLs make your life easier.
What can you store? #
One thing to remember when working with data attributes is that you can’t store objects in them. Well, you can if you serialize them, but we’ll save that for another post.
For now, just know that you’re pretty much limited to storing strings.
Reading/writing data attributes with JavaScript #
Using the delete button as an example, let’s look at how we can access this data with JavaScript.
// Here's our button var button = document.getElementById('your-button-id'); // Get the values var cmd = button.getAttribute('data-cmd'); var Change the values button.setAttribute('data-cmd', yourNewCmd); button.setAttribute('data-id', yourNewId);
Pretty simple, right? Now you can pass cmd and id to your app in an AJAX request or do whatever else you need to do with it.
Reading/writing data attributes with jQuery #
Here’s the same thing using jQuery’s .attr() method:
// Get the values var cmd = $('#your-button-id').attr('data-cmd'); var Change the values $('#your-button-id') .attr('data-cmd', yourNewCmd) .attr('data-id', yourNewId);
Don’t get this confused with jQuery’s .data() method. Although there is some overlap in how data attributes and .data() work, they’re two totally different things. If you’re not familiar with it, just stick with .attr() .
Using the dataset API #
HTML5 actually has an API just for working with this type of data. Alas, IE10 and below don’t fully support it, but it’s still worth mentioning.
Using the button example again, here’s how to get and set data attributes using the dataset API:
// Here's our button var button = document.getElementById('your-button-id'); // Get the values var cmd = button.dataset.cmd; var Change the values button.dataset.cmd = yourNewCmd; button.dataset.id = yourNewId;
Note how there’s no data prefix or dashes here. Similar to the way CSS properties work in JavaScript, you’ll need to use camel case notation. The dataset API converts each one so you’ll always have data-some-attribute-name in your HTML and dataset.someAttributeName in your JavaScript. Magic!
Things you can do with data attributes #
The examples above are very basic, but you can do so much with custom data attributes. Here are a few examples off the top of my head.
Filtering #
Say you have a list of things and you want to filter them by keyword. Just put the keywords into a data attribute and write a short script to loop through and show/hide them accordingly.
Here’s a quick and dirty filter using jQuery:
$('#filter').on('keyup', function() < var keyword = $(this).val().toLowerCase(); $('.cars >li').each(function() < $(this).toggle(keyword.length < 1 || $(this).attr('data-models').indexOf(keyword) >-1); >); >);
Styling #
It’s arguably better to use classes, but you can style things against data attributes too. Here’s how to apply a style if the element has a certain data attribute (regardless of its value). First, the HTML:
But what if we wanted to style it based on the data attribute’s value? This will work for any data-warning attribute that contains the word error:
Configuring #
Bootstrap uses data attributes as an HTML alternative to configuring plugins via JavaScript. Here’s an example of a popover:
A better way to store data #
Custom data attributes are widely used all over the web. The nice thing is that they work fine in older browsers, and they adhere to web standards moving forward. That means you can start using them today knowing that they won’t stop working tomorrow.
I’ve shown you a few common ways to use custom data attributes. What other uses can you think of? Have you used them before? Let me know by commenting below!
Written by Cory LaViska, a software engineer and Web Standards advocate responsible for Shoelace.style, Surreal CMS, and other open source things.
You can follow Cory on Twitter and GitHub.
HTML Web Storage API
With web storage, web applications can store data locally within the user’s browser.
Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.
Browser Support
The numbers in the table specify the first browser version that fully supports Web Storage.
API | |||||
---|---|---|---|---|---|
Web Storage | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
HTML Web Storage Objects
HTML web storage provides two objects for storing data on the client:
- window.localStorage — stores data with no expiration date
- window.sessionStorage — stores data for one session (data is lost when the browser tab is closed)
Before using web storage, check browser support for localStorage and sessionStorage:
if (typeof(Storage) !== «undefined») <
// Code for localStorage/sessionStorage.
> else <
// Sorry! No Web Storage support..
>
The localStorage Object
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
Example
// Retrieve
document.getElementById(«result»).innerHTML = localStorage.getItem(«lastname»);
- Create a localStorage name/value pair with name=»lastname» and value=»Smith»
- Retrieve the value of «lastname» and insert it into the element with >The example above could also be written like this:
// Store
localStorage.lastname = «Smith»;
// Retrieve
document.getElementById(«result»).innerHTML = localStorage.lastname;
The syntax for removing the «lastname» localStorage item is as follows:
Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!
The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:
Example
if (localStorage.clickcount) <
localStorage.clickcount = Number(localStorage.clickcount) + 1;
> else <
localStorage.clickcount = 1;
>
document.getElementById(«result»).innerHTML = «You have clicked the button » +
localStorage.clickcount + » time(s).»;
The sessionStorage Object
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.
The following example counts the number of times a user has clicked a button, in the current session:
Example
if (sessionStorage.clickcount) <
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
> else <
sessionStorage.clickcount = 1;
>
document.getElementById(«result»).innerHTML = «You have clicked the button » +
sessionStorage.clickcount + » time(s) in this session.»;
How to store and use data in HTML
When creating you HTML document, you can add/inject a javascript expression that contains your data.
console.log(`The value injected is: $`);
Data Block
Data Scheme
Example with a hello world text encode:
Data Attribute
In the HTML data attribute where you can store data for a element.
Json Module
You can also import data via a JSON module
import peopleInSpace from "http://api.open-notify.org/astros.json" assert < type: "json" >; const list = document.querySelector("#people-in-space"); for (const < craft, name >of peopleInSpace.people) < const li = document.createElement("li"); li.textContent = `$/ $`; list.append(li); >
Most elements that are used in the body of documents and applications are categorized as flow content. Flow content consists of flow elements intermixed with normal character data. (ifbodhead.
HTML An attribute in HTML is an XML attribute of an HTML element Attribute names are TR/html-markup/documents.htmlcase-insensitive. Classes and IDs are attributes used in the selection of element.
data block are a way to embed data in a html document. The well known is ld-json data block Inject json data in pre-rendered HTML Static pre-generated by the server (ie pre-rendering), the.
As a general rule, elements whose content model allows any flow content or phrasing content should have at least one node in its contents: that is palpable content (Can be manipulated ?) and that.
Phrasing content is: the text of the document, as well as elements that mark up that text at the intra-paragraph level. Runs of phrasing content form paragraphs. Most elements that are categorized.
The module implementation in Ecma Script (ES2015). An ES6 module is a Javascript file: automatically set in strict-mode with export statement and / or statement Everything inside a module is.
HTML5 Web Storage
In this tutorial you will learn how to use HTML5 web storage feature to store data on user’s browser.
What is Web Storage?
The HTML5’s web storage feature lets you store some information locally on the user’s computer, similar to cookies, but it is faster and much better than cookies. However, web storage is no more secure than cookies. Please check out the tutorial on PHP cookies to learn more about cookies.
The information stored in the web storage isn’t sent to the web server as opposed to the cookies where data sent to the server with every request. Also, where cookies let you store a small amount of data (nearly 4KB), the web storage allows you to store up to 5MB of data.
There are two types of web storage, which differ in scope and lifetime:
- Local storage — The local storage uses the localStorage object to store data for your entire website on a permanent basis. That means the stored local data will be available on the next day, the next week, or the next year unless you remove it.
- Session storage — The session storage uses the sessionStorage object to store data on a temporary basis, for a single browser window or tab. The data disappears when session ends i.e. when the user closes that browser window or tab.
Tip: The HTML5’s web storage feature is supported in all major modern web browsers like Firefox, Chrome, Opera, Safari and Internet Explorer 8 and above.
The localStorage Object
As stated earlier, the localStorage object stores the data with no expiration date. Each piece of data is stored in a key/value pair. The key identifies the name of the information (like ‘first_name’), and the value is the value associated with that key (say ‘Peter’). Here’s an example:
Example
// Check if the localStorage object exists if(localStorage) < // Store data localStorage.setItem("first_name", "Peter"); // Retrieve data alert("Hi, " + localStorage.getItem("first_name")); >else
Example explained:
The above JavaScript code has the following meaning:
- localStorage.setItem(key, value) stores the value associated with a key.
- localStorage.getItem(key) retrieves the value associated with the key.
You can also remove a particular item from the storage if it exists, by passing the key name to the removeItem() method, like localStorage.removeItem(«first_name») .
However, if you want to remove the complete storage use the clear() method, like localStorage.clear() . The clear() method takes no arguments, and simply clears all key/value pairs from localStorage at once, so think carefully before you using it.
Note: The web storage data (both localStorage and sessionStorage ) will not be available between different browsers, for example the data stored in Firefox browser will not available in Google Chrome, Safari, Internet Explorer or other browsers.
The sessionStorage Object
The sessionStorage object work in the same way as localStorage , except that it stores the data only for one session i.e. the data remains until the user closes that window or tab.
Let’s try out the following example to understand how it basically works:
Example
// Check if the sessionStorage object exists if(sessionStorage) < // Store data sessionStorage.setItem("last_name", "Parker"); // Retrieve data alert("Hi, " + localStorage.getItem("first_name") + " " + sessionStorage.getItem("last_name")); >else