Question

I've run into a little something that I can't figure out and I was wondering if you could have a go at it.

First off, there's this code:

<li class="mc002">
<ul>
    <li>
        <div class="label-container">
            <a class="btn">label 1</a>
            <a class="btn">label 2</a>
        </div>
        <div class="main-container">
            <div class="prj-title">
                <h3><a href="">New design for my website</a></h3>
                <div class="buttons">
                    <button data-role="none" class="btn smry">summary</button>
                </div>
            </div>
            <div class="summary">
            </div>
            <div class="prj-footer">
                <h6>filed under:</h6>
                <span>webdesign, webdevelopment, UX design</span>
                <h6>skills:</h6>
                <span>html5, css3, javascript, php</span>
            </div>
        </div>
    </li>

and the JavaScript to make "summary" slide down:

$('.main-container .smry').click(function () {
    $(this).closest(".summary").slideToggle(100);
});

The problem with this is that it doesn't work. Can you help me out, please?

Was it helpful?

Solution

The .closest() method doesn't find siblings or cousins, it starts with the current element (.smry, in your case) and goes up through the ancestors, stopping when it finds a match (or returning an empty jQuery object if there is no match).

Try this instead:

$('.main-container .smry').click(function () {
    $(this).closest(".main-container").find(".summary").slideToggle(100);
});

This navigates up to the closest containing .main-container element and then uses .find() to go back down to its associated .summary element.

Demo: http://jsfiddle.net/4a8JC/

Note that your code would need to be in a document ready handler and/or in a script block that appears after the elements in question.

(Note also that your summary div would need to have some actual content for this to make sense.)

OTHER TIPS

I'll suggest to use just $(".main-container .summary") instead of closest. It's a little bit heavy operation. And do you have something in .summary. If it is an empty I don't think that you will see something.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top