jQuery scrollTo going to far when accordion open

jQuery scrollTo going to far when accordion open

Hi there,

I have created an accorion using simple slideup/slidedow jquery. I have a list of images outside of this accordion. When each image is clicked it opens the accordion tab relating to that image title. This works well.

I now want to scrollTo the accordion item that theimage link has opened. I have done using this little bit of jQuery:

  1. $('html, body').animate({ scrollTop: target.offset().top }, 1000);

It work's but only when all the accordion items are closed when you click on the image. If one of the accordion items is already open then the scroll function goes too far or to a random place down the page.

How can I make this scroll to anchor acurate?

  1. $('.tab-trigger-mobile').click(function(e) {
               
                e.preventDefault();
                var selectMobileTriggerID = $(this).attr('id');
                $('.accordion__head').removeClass('open');
                $('.accordion__content').slideUp();
               
                $('.accordion__content-' + selectMobileTriggerID).slideDown();
                $('.accordion__head-' + selectMobileTriggerID).addClass('open');
                $('.accordion__content-' + selectMobileTriggerID).ScrollTo();
               
                var target = $('.accordion__content-' + selectMobileTriggerID);
                    window.scrollTo(0, 0);
                    if( target.length ) {
                    event.preventDefault();
                   
                    $('html, body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                }
               
            });

Above is the full code used. Each image has the class of 'tab-trigger-mobile'.

Thank you