I'm creating a small dynamic survey, with radio buttons, and I am trying to scroll to the next question when one question is answered.
The survey is built like this (basic survey)
<section class='question'>
<h2>Title of the question</h2>
<ul>
<li><input type="radio" class='choice'>Answer 1</li>
<li><input type="radio" class='choice'>Answer 2</li>
<li><input type="radio" class='choice'>Answer 3</li>
</ul>
</section>
The script for the animation is below
<script>
$(".choice").click(function() {
var next;
next = $(this).parent().next().find(".choice");
$("html, body").delay(1000).animate({scrollTop: next.offset().top}, 2000);
});
</script>
It works perfectly well when Answer 1 or 2 are selected, but it doesn't work for Answer 3. The console says "next" is undefined.
Any idea ?
Thank you for your help
I guess you have a multiple questions with radio answers and when you click a radio input you need to scroll to the next question. In this case you can watch for on change events on the radio buttons. When you get a on change event you get the container of the answer and then use .next()
to get the next question. If there is next question you scroll to it with a nice animation transition.
JS:
$('.choice').on('change', function() {
var nextQuestion = $(this).closest('.question').next();
if (nextQuestion.length !== 0) {
$('html, body').animate({
scrollTop: nextQuestion.offset().top
}, 1000);
}
});
Here's the JSFiddle: http://jsfiddle.net/hzda8e57/