Jeff
Jeff

Reputation: 480

jquery click bind not working when I use this

So I am trying to make a section that folds up when the title is clicked on. It works if I use the following but obviously folds all sections up instead of just the clicked on:

$(".foldUpSection").find(".header").click(function()
{
    $(".foldUpSection").find(".foldMeUp").slideToggle();
});

I switched it to

$(".foldUpSection").find(".header").click(function()
{
    $(this).find(".foldMeUp").slideToggle();
});

but this does nothing. Am I missing something to why it is not passing the this on click?

Here is the HTML

<div class="foldUpSection">
    <span class="header">Unprocessed EDIs</span>
    <div id="unprocessedEdi" class="foldMeUp">
    </div>
</div>

Upvotes: 0

Views: 78

Answers (3)

Anton
Anton

Reputation: 32581

Using $(this) and .find() made you target the wrong element.

Use .next() or .siblings(), find() searches for children, foldmeup is a sibling

   $(this).siblings(".foldMeUp").slideToggle();

or

 $(this).next(".foldMeUp").slideToggle();

DEMO

Documentation for .find()

Upvotes: 1

gvee
gvee

Reputation: 17161

In that context this refers to $(".foldUpSection").find(".header")

the find() function looks for descendants of a selector and $(".foldUpSection").find(".header") has no descendants with a class of foldMeUp.

Upvotes: 4

Joseph Silber
Joseph Silber

Reputation: 219920

If the DOM structure is not set in stone (so that you might have other elements between .header & .foldMeUp, use this:

$(".foldUpSection").find(".header").click(function()
{
    $(this).closest(".foldUpSection").find(".foldMeUp").slideToggle();
});

Here's the fiddle: http://jsfiddle.net/jEgK4/

Upvotes: 1

Related Questions