ValleyDigital ValleyDigital - 5 months ago 9
jQuery Question

Using jQuery, display different text beneath the list, for each list item that is clicked

I have an unordered list, and I would like to show text describing each list item, as each list item is clicked. I am having trouble with getting the text to display correctly. Can you assist?

<div>
<ul>
<li class="item">1</li>
<li class="item">2</li>
<li class="item">3</li>
<ul>
</div>

<div>
<ul>
<li id="one" class="selected">Description of Item 1</li>
<li id="two" class="selected">Description of Item 2</li>
<li id="three" class="selected">Description of Item 3</li>
</ul>
</div>

<script>

$(".item").click(function() {
$("li.selected").show('#id.li'));
});

</script>


As you can see, I am trying to get the text to display under each item that is selected, in a separate div. My jQuery is way off. I know I need a work-over on this. Thank you in advance.

Answer

I've added a custom data attribute to your list, so the items know which description belongs to which item.

When the DOM is ready we hide all descriptions. When an item is clicked, we hide all descriptions again and show the corresponding description for this item (identified by its id).

$(document).ready(function() {

  $("li.selected").hide(); // hide all descriptions

  $(".item").click(function() {
    $("li.selected").hide(); // hide all descriptions
    $("#" + $(this).data('desc')).show(); // show the description that belongs to the clicked item
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
  <ul>
    <li class="item" data-desc="one">1</li>
    <li class="item" data-desc="two">2</li>
    <li class="item" data-desc="three">3</li>
    <ul>
</div>

<div>
  <ul>
    <li id="one" class="selected">Description of Item 1</li>
    <li id="two" class="selected">Description of Item 2</li>
    <li id="three" class="selected">Description of Item 3</li>
  </ul>
</div>

Comments