'jQuery Auto Scroll to DIV - But Auto Scroll Works only on First Page

I'm creating Quiz site and have a confusing problem. Because explanation will show only after one answer is selected - that is "hidden" element I wrapped that element into visible DIV.

Code I'm using simply, after user clicks on answer auto-scroll to visible DIV within explanation wrapped inside.

My auto-scroll code is:

var elem = $('.scroll');
            if(elem) {
            $(window).scrollTop(elem.offset().top).scrollLeft(elem.offset().left);
        }

ISSUE: After user click on Continue button, on the next question, after answer is selected - nothing happens. Note - there's no page refresh after continue button, whole quiz is within same container, as a slider.

Live Quiz Example: Link for Quiz



Solution 1:[1]

i dont know where you will bind your code, but in the example site, each continue button have to bind your code with their own one '.scroll' element.

if just $('.scroll'), jquery selector will find all of .scroll class element (found 40 in the example site) and offset() function will be executed with first of all .scroll elements (not a valid index of them)

so, for example,

the continue button in the second quiz(Benjamin Franklin) should bind with second $('.scroll').eq(1) element. not a $('.scroll').

var elem = $('.scroll').eq(0);
if(elem) {
 $(window).scrollTop(elem.offset().top).scrollLeft(elem.offset().left);
}

i can't see whole source in that page. but maybe you can bind the event once and just assign index to eq().


added

i tracked event and found your code in the 'quiz-trivia.js'.

changed one thing.

(roughly write down that i tracked and answer)

  1. click answer .
  2. on click event of '.wpvqgr-answer', wpvqgr.selectAnswer() function will be executed.
  3. then in selectAnswer(), need to find '.scroll' element in same area(ex: in first page Albert Einstein, first element of 40 '.scroll'. so
// The function is given a parameter called question_id which indicating the question index. 
// we can find the same area .scroll with this index

// not $('.scroll').
var elem = $('.scroll').eq(question_id);
  1. '.scroll' of same area will be found. and behind, your code will work correctly

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1