jQuery Accordion - will it scroll to the top of the open item?

Viewed 53245

With the jQuery accordion control, how can I have it scroll to an item I've selected when it is off the screen?

When:

  • I have an accordion item with contents larger than the viewable window
  • I scroll down to the second accordion item
  • I click the second accordion item to display it
  • The first accordion option collapses, and the second opens, but slides off screen.

Is there an option for the accordion to scroll to the second item?

11 Answers

As I want collapse to be true I added an if test to cancel out the error of all items being collapsed. I also didn't want the header to be exactly at the top of the page, so I lowered the scrollTop location by 100:

  $(document).ready(function() {
    $(".ui-accordion").bind("accordionchange", function(event, ui) {
      if ($(ui.newHeader).offset() != null) {
        ui.newHeader, // $ object, activated header
        $("html, body").animate({scrollTop: ($(ui.newHeader).offset().top)-100}, 500);
      }
    });
  });

Solution from Martin works great. However when you add this code it will scroll to the top always, no matter if your accordion is visible on the page or not.

If you want to scroll to the top only when your accordion content larger than the viewable window, then use next code:

$(document).ready(function() {

    function isScrolledIntoView(elem)
    {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }

    $(".accordion-inner").bind("accordionchange", function(event, ui) {
      if ($(ui.newHeader).offset() != null) {
        if (!isScrolledIntoView(ui.newHeader))
        {
            ui.newHeader, // $ object, activated header
            $("html, body").animate({scrollTop: ($(ui.newHeader).offset().top)-100}, 500);
        }
      }
    });
  });

Simply use this function on window.load

$(function() {
    var icons = {
    header: "ui-icon-circle-plus",
    activeHeader: "ui-icon-circle-minus"
    };
    $( "#accordion" ).accordion({
    icons: icons, autoHeight: false, collapsible: true, active: false,
    activate: function(event, ui){
        var scrollTop = $(".accordion").scrollTop();
        var top = $(ui.newHeader).offset().top;
     //do magic to scroll the user to the correct location

     //works in IE, firefox chrome and safari
        $("html,body").animate({ scrollTop: scrollTop + top -35 }, "fast");
       },



    });

    });

perfectl wokring

Related