im trying to get this button to show a hidden div onClick
within each li that will show over the post div in an absolute positioning. The problem is, on click, it's showing all of the hidden div's for all li's. Im using wordpress + buddypress, so each li's id has a unique ID
<li id="activity-<?php bp_activity_id(); ?>" class="activity" >
<div id="post"></div>
<div class="action">
//my pop in stuff
</div>
<div id="post-actions-bar">
<button id="show">show</button>
</div>
</li>
and here's my jquery that I thought would work.
NOTE: I'm using .on()
because there will be li's added dynamically.
$(document).on( 'click' , '.activity button#show' , function() {
$('.action').show();
});
In a sense it does work, but it shows all of the .action div's
for every li on the screen, I only want to show the one for that li's button that was clicked. I tried using .each()
but It's not working. I'm ding something wrong (obviously lol)
Any ideas?
You need to use
$(this).closest('.activity').find('.action')
instead of$('.action')
.The reason for this is pretty simple - when you use
$('.action')
you simply retrieve all elements matching the selector.action
which is completely unrelated to the event.Within the event handler
$(this)
refers to the one button that was clicked. So what you need to do is start from$(this)
and traverse the DOM tree to get to the one.action
that you want to show.This is one way to do it, which I find preferable:
As an aside, your HTML implies that you are using the same
id
value for multiple elements. That's illegal and should be fixed -- it's only a matter of time before it causes trouble. Most of the time it's fine to assign a sharedclass
to your elements instead of the sameid
and work with that.Here is a fiddle for you:
I'd use the ul instead of the document to catch the click event
You can't do them with a single bind since
.action
can't be reached from.activity
orbutton#show
using the same method. You can do something like this: