3

I'm a jQuery newbie as of this morning, and this is the code I've come up with to show a div that accompanies the anchor that calls it, inside a div with the class 'foo'. It doesn't work :P

$('div.foo').children('a').click(function(event){
    event.preventDefault();
    if ($(this).closest('div').('div').is(':hidden')) {
        $(this).closest('div').('div').show("slow");
    } else {
        $(this).closest('div').('div').hide("slow");
    }
});

HTML:

<div class="foo">
    <a href="#" title="">Click me!</a>
    <div>And this will appear!</div>
</div>

I'd like to be able to have multiple identical foo divs (apart from the nested div's actual content of course), and all I need to do is assign the containing div the 'foo' class in order to cause the containing anchor to show the containing div on click.

Is this kind of thing even possible? Thanks in advance for responses.

2 Answers 2

6

Try this

$('div.foo a').click(function(event){
  event.preventDefault();
  $(this).next().toggle('slow');
});
Sign up to request clarification or add additional context in comments.

Comments

1

Try this instead (assuming 'div.faq' is supposed to be 'div.foo', based on the HTML):

$('div.foo').children('a').click(function(event){
    event.preventDefault();

    var parent = $(this).closest('div'),
    child = $('div', parent);

    if (child.is(':hidden')) {
      child.show("slow");
    } else {
      child.hide("slow");
    }
});

1 Comment

Sorry, was indeed meant to be 'div.foo'. Thanks for the response, this also works perfectly - though Colin's code is a little cleaner :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.