jQuery data- attributes

Used with buttons and DIVs

by m4xout

HTML

<p>The jQuery <code>data-</code> attribute relies on you to set up attributes in tags in your HTML and also to name corresponding containers (e.g. DIVs) appropriately. The extra work pays off by allowing you to write a very simple function that can handle dozens or hundreds of elements on your page (although this example shows only two). See a <a href="http://macloo.github.io/jquery_exercises/ex03.html" target="_blank">full-size example</a> and <a href="https://github.com/macloo/jquery_exercises" target="_blank">GitHub repo</a>.</p>

<button class="name" data-person="#rama">
  Rama the Hero
</button>
<button class="name" data-person="#sita">
  Sita the Heroine
</button>
<div class="character" id="rama">
  <p>Handsome Rama is the avatar of Vishnu.</p>
</div>
<div class="character" id="sita">
  <p>Sita was kidnapped by the evil Ravana.</p>
</div>

CSS

#rama {
  background: #239d9a;
}

#sita {
  background: #ca6996;
}

div {
  padding: 20px;
  margin-top: 10px;
}

JavaScript

// jQuery is enabled


// hide all the divs
$('.character').hide();


// this function will work for an infinite number of buttons and divs - if the classes and IDs are set up correctly in HTML 
$('.name').click(function() {
  // hide any open div
  $('.character').hide();
  // get value of data attribute from the thing that was clicked 
  var person = $(this).data('person');
  $(person).slideDown();
});