Object data-attribute

Object data-attribute

by Adi Jaya

HTML

<div class='demo' 
  data-config='{ 
      "backgroundColor" : "#ffc1d6", 
      "color": "#E91E63",
      "borderColor" : "#ff9bbd"
    }'>
  hello world
</div>

<div class='demo' 
  data-config='{ 
      "backgroundColor" : "#00BCD4", 
      "color": "#cbf7fd",
      "borderColor" : "#0598ab"
    }'>
  hello world
</div>

<div class='demo' data-config='{ "backgroundColor" : "yellow" }'>
  hello world
</div>

CSS

html {
  font-size: 16px;
}
.demo {
  padding: 1em;
  border: 1px solid silver;
  border-radius: 4px;
  margin: 1em 0;
}

JavaScript

$( ".demo" ).each(function() {

	if( $( this ).attr( "data-config" ) ){
    
		var dataConfig = $( this ).data( "config" );
        
  		$( this ).css({
  			"background-color" : dataConfig.backgroundColor,
      		"color" : dataConfig.color,
      		"border-color" : dataConfig.borderColor
		});

  }

});