jquery accordion scrolls to top on activate, then breaks on second click
jquery, jquery-ui
Solution
`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.
Problem
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.