tags:

views:

37

answers:

1

Hi,

I am trying to make a poll application with java and jQuery for UI. The questions will be visible but answers will be hidden. I want that when a user clicks a question the answers will slide down. But in the implementation should i make every question and it's answers in a different 'div' element. What should be my outline?

+2  A: 

There are several ways to solve the problem, but I'd do something like this:

<div class="question">
   Question
   <div class="answer" style="display: none;">
      Answer!
   </div>
</div>

And script-wise

$(document).ready(function() {
   $('.question').click(function() {
       $(this).find('.answer').slideDown('fast');
   });
});
David Hedlund
I would probably rather do `$('.answer', this)` than `$(this).find('.answer')`, but it's more a matter of taste than anything else.
Tomas Lycken
@Tomas Lycken: yes, that's probably preferable! there should be a slight overhead. i think they translate to the same, but yours is without the round-trip of wrapping `this` in `$`
David Hedlund
@David: Should i create a div for every question? Because i will have more than 20 questions. and is it better to add id attribute for each div?
yakup
@yakup85: yes, one div for each question. and they should all have the same *class* so that the jQuery can find them all in one go. don't bother with ID, because ID has to be unique for each element. regardless of how many copies you make of HTML like the one I've posted above, you don't have to change a bit in the jQuery script for it to work on all questions.
David Hedlund
@David: I would guess, although I haven't looked at the source code, that `jQuery.find()` just returns what I did. However, you don't need to wrap `this` in `$` either - it is already a wrapped set, only Visual Studio can't see that if you don't wrap it. So `this.find('.answer')` is perfectly fine - and for less than thousands of questions, I doubt that there's really a perf hit.
Tomas Lycken
@Tomas Lycken: yeah, it won't be measurable =) i think you're wrong about `this` though. in an event listener, the context is the DOM node, not pre-wrapped in `$`. So `$('div').click(function() { console.log(typeof this.find); });` logs `undefined`.
David Hedlund
@David: Ha! Good catch there. You're right, of course =)
Tomas Lycken
@David: Thanks!
yakup