joecampbelluk
joecampbelluk

Reputation: 81

jquery accordion scrolls to top on activate, then breaks on second click

I am trying to create a jquery accordion which scrolls to the top of the link that is clicked. The following code achieves this, but breaks when the link is clicked for a second time:

$(function () {
    $("#paper-types").accordion({
        heightStyle: "content",
        collapsible: true,
        active: false,
        activate: function (event, ui) {
            var scrollTop = $(".accordion").scrollTop();
            var top = $(ui.newHeader).offset().top;
            $("html,body").animate({
                scrollTop: scrollTop + top - 35
            }, "fast");
        }

   });
});

This can be seen on a jsfiddle at:

http://jsfiddle.net/6PPEZ/1/

What is broken in this code that stops it working on the second click?

EDIT: One thing that I have noticed is that it only stops working if you click the title to collapse the accordion. If you instead open the next link, the original link can be opened again without a problem.

Upvotes: 3

Views: 4589

Answers (2)

PSL
PSL

Reputation: 123739

ui.newHeader will be empty object in case of collapsing the accordion panel, that is throwing it off when you try to access top of undefined (offset() of empty jq object returns undefined). Just add a check if(!ui.newHeader.length) return;

    activate: function (event, ui) {
        var scrollTop = $(".accordion").scrollTop();
        if(!ui.newHeader.length) return;
        var top = $(ui.newHeader).offset().top;
        $("html,body").animate({
            scrollTop: scrollTop + top - 35
        }, "fast");
    }

Demo

From Documentation

If the accordion is collapsing, ui.newHeader and ui.newPanel will be empty jQuery objects.

Upvotes: 5

Tats_innit
Tats_innit

Reputation: 34107

Working demo http://jsfiddle.net/EU9LE/

I have changed things which were not needed,

  • instead of $("html,body") use this
  • Also instead of offset use the $(ui.newHeader).top;

This will fit the need :)

Code

$(function () {
    $("#paper-types").accordion({
        heightStyle: "content",
        collapsible: true,
        active: false,
        activate: function (event, ui) {
            var scrollTop = $(".accordion").scrollTop();
            var top = $(ui.newHeader).top;
            $(this).animate({
                scrollTop: scrollTop + top - 35
            }, "fast");
        }

   });
});

Upvotes: 1

Related Questions