1

I have a list of questions that users should fill. Questions of type yes or No are those that can shift to another question number depending what is chosen. for example a question in radio button.

  1. Are your marriage? yes No

$('body,html').animate({scrollTop: $("#"+anyQuestionId).offset().top}, 1000);

I want to scroll to question number 2 if the response is yes and question number 10 when No. This code sample is not taking me to the exact question number.

how can I achieve this in jquery?

LL Janneh
  • 190
  • 1
  • 2
  • 14
  • Why not just create a `div` with a unique `id` attribute, and use jQuery to write the text of the current question into that element? Then, depending on the answer the visitor gives, use jQuery to choose the next question, clear the content of the `div` and write the text of that new question into it? I think scrolling will always be hit-and-miss, so you're better off simply writing and clearing text within a specific element. – Bobulous Dec 28 '16 at 13:17
  • can you please give sample code in JSFiddle – LL Janneh Dec 28 '16 at 13:22
  • In order to answer this question we need more information. Here's a sample fiddle that works (https://jsfiddle.net/sx0dg8nt/), but without more context from you, there is no way to find out what goes wrong. As already stated by others; that line of code you included looks correct, so the problem must be somewhere else in your code. – Rogier Pennink Dec 28 '16 at 13:24

3 Answers3

1

The only thing you need to change is the value for scrollTop. You can simply add or subtract the number of pixels that you'd like to offset the scroll. For example:

$('html, body').animate({
        scrollTop: $("#"+anyQuestionId).offset().top + 50
}, 1000);

Here's an example. If you click on the first element, it will scroll 50 pixels past where it normally would.

https://codepen.io/simsketch/pen/JbQQML

Hope this helps!

Elon Zito
  • 2,872
  • 1
  • 24
  • 28
0

Here is it with working example Simple jQuery scroll to anchor up or down the page...?

If you want to check what was chosen, you can put as handle of event of the field you want to react to and in this handle you can check the value and if its what you want you will scroll otherwise not, but think about it wisely (what even you chose and if it will not be too much annoying for the user).

Community
  • 1
  • 1
user1097772
  • 3,499
  • 15
  • 59
  • 95
0

you need to watch and capture the radio button click event, like this:

$('.radio input').on('click', function(el){
    console.log( $(this).prop('checked') )
    if( $(this).prop('checked') ){
        $('body,html').animate({scrollTop: $(".red").offset().top}, 1000);
    }
})

here is the demo: http://codepen.io/mkdizajn/pen/ObeepY?editors=1010

hth, k

Kresimir Pendic
  • 3,597
  • 1
  • 21
  • 28