Reputation: 2247
is it possible to do this with a loop so i dont have to write click function for every div?
$("#q1").click(function(){
$("#ans1").slideToggle("fast");
});
$("#q2").click(function(){
$("#ans2").slideToggle("fast");
});
$("#q3").click(function(){
$("#ans3").slideToggle("fast");
});
$("#q4").click(function(){
$("#ans4").slideToggle("fast");
});
$("#q5").click(function(){
$("#ans5").slideToggle("fast");
});
$("#q6").click(function(){
$("#ans6").slideToggle("fast");
});
$("#q7").click(function(){
$("#ans7").slideToggle("fast");
});
$("#q8").click(function(){
$("#ans8").slideToggle("fast");
});
where every id has a num that is same as the id num inside click function like #q8 has ans#8 and if i add another id #q9, #ans9 i dont have to write click function?
every div also has a class... please tell me how can i do it when i click on question its ans should show
<div id="q1" class="question"><span id="q">Q: </span><span id="ul">How Do I Choose a Web Designer?</span></div>
<div class="answer" id="ans1">some text</div>
Upvotes: 2
Views: 964
Reputation: 1361
What Can be done is .. put both your question and answer in a block .. Say ...
<div class="qa-block">
<div class="question">Q: How Do I Choose a Web Designer?</div>
<div class="answer">some text</div>
</div>
Then change your script to ..
$('.question').on('click', function() {
$(this).closest('.answer').slideToggle('fast');
});
This will generalize your solution and avoids the use of IDs
Hope this helps..
Upvotes: 3
Reputation: 45124
You can do this like below using one function. Add a attribut to the question div data-answerid
. It contains which answer to be shown. You don't have to repeat all to implement this functionality.
<div class="question" data-answerid="ans1">
<span id="q">Q: </span>
<span id="ul">How Do I Choose a Web Designer?</span>
</div>
<div class="answer" id="ans1">some text</div>
<div class="question" data-answerid="ans2">
<span id="q">Q: </span>
<span id="ul">How Do I Choose a Web Designer?</span>
</div>
<div class="answer" id="ans2">some text</div>
$(".question").click(function(){
var answer = $(this).data('answerid');
$("#"+answer).slideToggle("fast");
});
Upvotes: 1
Reputation: 1
I'd actually use a class for all the question divs, write smthing like:
$('.questionclass').click(function {
var qnr = this.attr('id'); //gets div ids...
var anr = qnr.replace(/[^0-9]/g, ''); //strips id of non-numeric characters
$("#ans"+anr).slideToggle("fast"); //toggles the answer div
});
I'm kind of sleepy so there may be some mistakes, but it should point you in the right direction.
Upvotes: 0