Daniel9
Daniel9

Reputation: 1

Jquery accordion panel move to top when opened

I am trying to make it so when an accordion panel is clicked and opened it will move to the top so user won't have to scroll down to see the content. Here is what I have so far, but nothing I try seems to work and when I add and acitvate function the whole accordion feature stops working. Any help is greatly appreciated. Thanks.

$(function () {

     $(".accordion").accordion({
        collapsible: true,
        active: false,
        heightStyle: "content", 
        animate: 150,

             //This makes it possible for multiple panels to be open at the same time

            beforeActivate: function(event, ui) {
             // The accordion believes a panel is being opened
            if (ui.newHeader[0]) {
                var currHeader  = ui.newHeader;
                var currContent = currHeader.next('.ui-accordion-content');
             // The accordion believes a panel is being closed
            } else {
                var currHeader  = ui.oldHeader;
                var currContent = currHeader.next('.ui-accordion-content');
            }
             // Since we've changed the default behavior, this detects the actual status
            var isPanelSelected = currHeader.attr('aria-selected') == 'true';

             // Toggle the panel's header
            currHeader.toggleClass('ui-corner-all',isPanelSelected).toggleClass('accordion-header-active ui-state-active ui-corner-top',!               isPanelSelected).attr('aria-selected',((!isPanelSelected).toString()));

            // Toggle the panel's icon
            currHeader.children('.ui-icon').toggleClass('ui-icon-triangle-1-e',isPanelSelected).toggleClass('ui-icon-triangle-1-s',!isPanelSelected);

             // Toggle the panel's content
            currContent.toggleClass('accordion-content-active',!isPanelSelected)    
            if (isPanelSelected) { currContent.slideUp(); }  else { currContent.slideDown(); }

            return false; // Cancels the default action
        }

});

Upvotes: 0

Views: 868

Answers (1)

popnowlin
popnowlin

Reputation: 15

Here's what I was able to do, using multiple articles in stackoverflow as a resource. I came up with a simple javascript function that uses the jquery animate to scroll to the top of any element on the page. I called it totop():

function totop(element) {
    offset = element.offset();
    $("html").animate({scrollTop:offset.top},500);
}

Then in the document ready function I define an event to execute the function when a panel on the accordion, identified by ID accord-1, is clicked:

$("#accord-1").on("accordionactivate",function(event,ui) {
    totop(ui.newHeader);
});

This works just the way my client wanted. I use it on multiple pages. Here's a simple example page:

test accordion

Upvotes: 1

Related Questions