2

I'm currently using HTML data attributes to display basic information when an element is clicked using $(this). For example, I have the following HTML snippet:

$('.element').on('click', function(e) {
  e.stopPropagation();
  $('#info').slideDown();

  var title = $(this).data('title');
  var desc = $(this).data('desc');
  var icon = $(this).data('icon');

  var info = $('#info');

  info.html('<div class="sub-info"><h1>' + title + '</h1><h1 class="icon">' + icon + '</h1></div><div class="side-info"><p>' + desc + '</p></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element" data-title="title" data-desc="desc" data-icon="H">

It's working as intended but I need more information and keeping it in objects would be a lot cleaner I think. Could anyone point me in the right direction?

0

1 Answer 1

2

In this case you could put all the data in an object, then use the property names of that object in the data attribute to perform the lookup in the click event handler, something like this:

var data = {
  foo: {
    title: 'title #1',
    description: 'description #1',
    icon: 'icon #1'
  },
  bar: {
    title: 'title #2',
    description: 'description #2',
    icon: 'icon #2'
  }
};

$('.element').on('click', function(e) {
  e.stopPropagation();
  var obj = data[$(this).data('key')];
  $('#info').html('<div class="sub-info"><h1>' + obj.title + '</h1><h1 class="icon">' + obj.icon + '</h1></div><div class="side-info"><p>' + obj.description + '</p></div>').slideDown();
});
#info {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element" data-key="foo">Lorem</div>
<div class="element" data-key="bar">ipsum</div>

<div id="info"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Rory, this is exactly what I was thinking of. Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.