tags:

views:

51

answers:

4

Maybe it's because it's Friday but I'm stuck on a simple problem. I'm building a FAQ page where a user clicks on a question, revealing the answer beneath it. I'm trying to get the next() function to just grab the next instance of an "answer" div but, despite not getting any JS errors, the hidden div isn't showing.

Here's the code:

.answer { display:none; }


$("a.question").click(function(){
 $(this).next(".answer").toggle();
}); 

<a href="#" class="question">Queston 1</a>
<div class="answer">Answer 1</div>

<a href="#" class="question">Queston 2</a>
<div class="answer">Answer 2</div>
+2  A: 

Use:

$(function(){
    $("a.question").click(function(){
     $(this).next().toggle();
     return false;
    }); 
});
Sarfraz
+1  A: 

Make sure to wrap your code in a document.ready, like this:

$(function() {
  $("a.question").click(function(){
    $(this).next(".answer").toggle();
  }); 
});

Without document.ready it's running the selector $("a.question") and not finding anything, because the links aren't there/ready yet, you can see this by doing alert($("a.question").length);. By putting it in document.ready it doesn't run the code to look for the elements until they are in the DOM and ready to go.

Your code itself works fine, see a demo here. You may also be interested in .slideToggle() if you want a nice effect, you can see it working here.

Nick Craver
@downvoter - Helps to say what's incorrect about the answer, oh I had a typo in "you", was that it?
Nick Craver
+2  A: 

That looks like it should work fine.. have you tried just $(this).next().toggle()?

Jeriko
+3  A: 

It works for me.

You probably have some other element between the question and the answer.

If so, change it to

$(this).nextAll(".answer:first").toggle();

Alternatively, you might be running your code in the <head> tag, before the <body> is parsed.

If so, move your <script> below the question tags, or wrap it in $(function() { ... });.

SLaks
Wow... `nextAll()`... you learn something new everyday :)
Matt
jsbin.com <- now that's pretty cool!
Jeriko
Yeah, I had it wrapped in <p> tags. I forgot to put that in the original question. Apologies, all.
jon_brockman