How do I keep the Jquery toggle function opening in the same place?

I am using the Jquery Toggle() function like this:

    $("#btnbag1a").click(function(){
        $("#bag1a").toggle();
    });

It opens and shuts like a charm. Unfortunately, each time I use the button, it takes me to the top of the page, and I have to scroll down to see what was opened. Very poor UX.

I am using materializecss and wonder if their code is causing this problem.

Is there a way to make the show/hide keep the content in view? I tried adding this windown.location snippet to it and it did not work; it still went to the top of the page:

    $("#btnbag1a").click(function(){
        $("#bag1a").toggle();
        window.location.assign('#bag1a');
    });

A fuller sense of this code is in Wordy Jquery toggle

Could the following code be integrated in some way? It is used to open the accordion then scroll to the top of the accordion contents:

  $(document).ready(function(){
    $('.collapsible').collapsible({
      accordion : false // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    });
   $('.collapsible-header').bind('click',function(){
            var self = this;
            setTimeout(function() {
                theOffset = $(self).offset();
                $('body,html').animate({ scrollTop: theOffset.top - 100 });
            }, 310);
        });
  });

I spoke too soon. It works when toggling it to show, but when tapped to hide, it jumps to the top of the page and sticks.

Maybe it doesn’t scroll to where you tapped it because the table is hidden and the code can no longer locate the table’s id. Is this thinking correct?

[ checking…]

Yes this thinking is correct. I swapped out “this” for the button id:

    $("#btnbag1a").click(function(){
        $("#bag1a").toggle(function(){
             jQuery('html, body').animate({
                 scrollTop: jQuery('#btnbag1a').offset().top
             }, 1000);
        });
    });

Upon tapping the button to open, it gracefully scrolled to the button, but in so doing, it scrolled the table up out of view (the button is at the bottom of the table that it’s to hide/show).

[checking…]

Moving the button to the top of the table works!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.