Skip to content Skip to sidebar Skip to footer

Set Data- Html5 Value By Default

I have this small code that put some preset style to a div with custom attributes, that attributes set the src and an APA text to an img tag, also generate a button with a zoom opt

Solution 1:

You're seeing this behavior because jQuery data() method attempts to convert attributes into Javasript values, below is an excerpt from the manual:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null).

To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.

According to HTML5 specification regarding boolean attributes:

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

This is probably the reason why jQuery returns empty string as value for data-sg-img-zoom attribute.

Testing for presence of the attribute

If you would like to test only initial presence of the attribute data-attr such as <div data-attr> then both jQuery data() and attr() return undefined, so the following code could be used:

var is_set = (typeof $(el).attr('data-attr') === 'undefined') ? true : false;

or

var is_set = (typeof $(el).data('attr') === 'undefined') ? true : false;

Testing for presence of the attribute and true/false values

If you would like to test for presence of the attribute data-attr AND values true/false such as <div data-attr>, <div data-attr="true"> and <div data-attr="false">, use the code below.

var el_data_attr = $(el).data('attr');
var is_set = (
      // If attribute is specified
      typeof el_data_attr !== 'undefined' 
      // And no value is given or value is evaluated to true
      && (el_data_attr === '' || el_data_attr)
   ) ? true : false;

As a side effect, attribute values 1, foo will also be treated as true; and 0, null, NaN will be treated as false.

Solution for your example

Since you retrieve all data- attributes with single data() call, you need to use the following code:

var $meZoom = (
      $meData.hasOwnProperty('sgImgZoom') 
      && ($meData.sgImgZoom === '' || $meData.sgImgZoom)
) ? true : false;

Post a Comment for "Set Data- Html5 Value By Default"