Michael Pon Michael Pon - 4 months ago 24
jQuery Question

display block with event target id

I'm try to display an item inside a list that has a class which is exactly the same ID on the other list. This would be activated when I click on the other list then it will find a match class on the other list then display it.

Here is the code I'm using basically the first list is in

display:none;

List 2 is my menu on which in the list 1 would you like to display.

The first list should only have one visible item at a time.

Fiddle is here

HTML

<div id="gallery-container">
<li class="1723"><p>
123
</p></li>
<li class="1725"><p>
456
</p></li>
</div>
<ul id="gallery-list">
<li id="1723">
<strong>qwertyuiop</strong>
</li>
<li id="1725">
<strong>asdfghjkl</strong>
</li>
</ul>


SCRIPT:

$("#gallery-list li").click(function() {
alert(event.target.id);
$("#gallery-container li .wc-gallery").css("display", "none");
});

window.onload = function () {
$("#gallery-container li p").css("display", "none");
}


CSS:

#gallery-container li p {display:none;}

Answer

It's bad bad to use the same id in one HTML document. Never do this. Nobody likes that, jQuery doesn't like that. I don't like it. Try using a class or a data property.

But.. scratch that.. you are not really trying to do that. But still.. it's better to use a data property :)

Anyways, to accomplish this with a data property, you can do something like this:

html

<div id="gallery-container">
  <li data-id="1723">
    <p>
      123
    </p>
  </li>
  <li data-id="1725">
    <p>
      456
    </p>
  </li>
</div>
<ul id="gallery-list">
  <li data-id="1723">
    <strong>qwertyuiop</strong>
  </li>
  <li data-id="1725">
    <strong>asdfghjkl</strong>
  </li>
</ul>

js

$("#gallery-list li").click(function() {
  var id = $(this).data('id');
  $("#gallery-container").find('li').each(function() {
     $(this).find('p').toggle($(this).data('id') === id);
  });
});

jsfiddle