Menu

Hooking with data attributes

If your content changes dinamically, – for example you’ve got an AJAX page load, to imporve interactivity – you can easyly put your current content inside the target HTML tag, without selecting each of them one by one. Here is an example:

 

The jQuery:

(function($) {
  // Data
  var data = {
    title: 'A title',
    date: 'Jan 15th, 2015 @ 15:03 ',
    content: 'This is The Content',
    author: 'anonymus'
  };
  // Loop to place the content
  for(var x in data) {
   $('#'+x).html(data[x]);
  }
})(jQuery);

 

The Html:

<article>
  <h1 id="title"></h1>
  <div id="date"></div>
  <div id="content"></div>
  <div id="author"></div>
</article>

Have something on your mind?