KMP
KMP

Reputation: 35

Accordion to scroll to current open item

The below is a simple accordion call out I have used for some time. Some of the open items contain a lot of text and when another item is chosen I need it to scroll to the selected open item. I've tried several times with variations from other posts using scrollTo but have had no success. Any help would be greatly appreciated.

$(document).ready(function() {

//ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING)
$('.turn1').click(function() {

    //REMOVE THE ON CLASS FROM ALL BUTTONS
    $('.turn1').removeClass('on');

    //NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
    $('.turn2').slideUp('normal');

    //IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
    if($(this).next().is(':hidden') == true) {

        //ADD THE ON CLASS TO THE BUTTON
        $(this).addClass('on');

        //OPEN THE SLIDE
        $(this).next().slideDown('normal');
     } 

 });

 $('.turn2').hide();
 $("#open").trigger('click');
 });

<script type="text/javascript">
$(function(){
    $('.turn1').click(function(){
        $.scrollTo(this)                                                 
    })
});
</script>

I also have this script which works nicely but having trouble with making the first accordion item to not jump down to the middle of the page where the first accordion item lives.

<script type="text/javascript">
$("#accord_holder").accordion({
autoHeight: false,
collapsible:true,
navigation:true,
active:false,
change: function(event, ui) {
    $(window).scrollTop(ui.newHeader.position().top - 1);
}
});
 </script>

Upvotes: 0

Views: 4353

Answers (1)

Itay
Itay

Reputation: 16777

Use jQuery's position and scrollTop():

<script type="text/javascript">
$(function(){
    $('.turn1').click(function(){
        $("html, body").scrollTop($(this).position().top);
    });
});
</script>

Upvotes: 2

Related Questions