jQuery: using custom data on slideshows

jQuery: using custom data on slideshows

How to use custom data with the $.data() and .data() jQuery methods on slideshows.

jQuery stores DOM data with two methods, namely $.data() (low-level) and .data() (high-level). Both can be used to attach data to HTML elements, exactly as you can do with the custom HTML5 data attributes. These features are handy when you have to deal with transitional element states.

A slideshow is a typical example of a set of elements which change their state during the script's execution. A slide or an image can be shown, hidden or moved. Here is where custom data come into play.

Suppose that you want to associate the current index to each slide:


$('div.slide', '#slider').each(function(i) {
	var $slide = $(this);
	$slide.data('data-index', i);
});

This is the same as the following HTML5 code:


<div id="slider">
	<div class="slide" data-index="0"></div>
	<div class="slide" data-index="1"></div>
	<div class="slide" data-index="2"></div>
</div>

Then you can retrieve a slide's index by simply accessing the corresponding data attribute:


var index = $slide.data('data-index');

We said that slideshow are characterized by transitional states. Usually we mark these states with special CSS classes, but there's a fastest and safer way. Imagine that you need to tag a slide when it's visible:


var $slide = $(this);
var $visibleHidden = ($slide.is(':visible')) ? 'visible' : 'hidden';
$slide.data('data-visibility', $visibleHidden);

Then you can try a simple check:


if($.hasData($slide)) {

	if($slide.data('data-visibility') == 'visible') {
	
		//...
	
	}

}

This can also be applied to a slide that has been already moved. The only thing you have to do is to check the correct CSS property and set your element's data accordingly.