Monday , 20 November 2017
Home / Programming / JavaScript / Data Attribute – Advanced JavaScript Tutorial
Data Attribute
Data Attribute

Data Attribute – Advanced JavaScript Tutorial

HTML5 is fairly new and it’s slowly being adopted by all web browsers today. A special feature of HTML5 is the ability to define custom data attributes. A data attribute is your own attribute that can contain information about an element. Let’s update our document to this.

To create a data attribute, you simply create an attribute with the data- prefix to the name of your attribute. In our case, we have a data attribute named data-color. Inside this attribute, you can store any kind of value you want. We store red in this attribute.

Let’s learn how to grab this in our script. Clear your script and add this bit of code.

As usual, we grab the the element with the getElementById() method. We store this in a variable named div. Next, we create a variable that will store the data attribute we have in our div tag. To grab the data attribute, you access the dataset property. Inside this property, you can access all data attributes you created specific to an element.

Lastly, we update the CSS style of our div tag to the value inside our data-color attribute.  You can create as many data attributes as you want. You can have any kind of values inside your data attributes.

Conclusion

The most common reason for using data attributes is so that you store information about the web page or information about an element. A common example is slideshows. You can have the user customize the x and y positions of a slide. Same thing goes for the animation. They won’t have to know any JavaScript in order to customize the slideshow. The data attribute only works in Google Chrome and Safari. It’s still relatively new. For more information about data attributes, then go here.

http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

About Jasko Koyn

Check Also

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

Your email address will not be published. Required fields are marked *

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link