Alex
Alex

Reputation: 929

Scroll to the top of the element click in accordion jQuery

I'm making an accordian, everything works fine, the thing is the content of each element is pretty large and I can't make the element to scroll at the top of title to start reading at the top of the element clicked, I'm trying with jQuery animate but is not working.

HTML

<dl class="FrecuentlyAsked">
  <dt>
    <h1 data-accordian-title="#accordian-1">Title</h1>
  </dt>
    <dd id="accordian-1">
       Content goes here
    </dd>
  <dt>
    <h1 data-accordian-title="#accordian-2">Title 2</h1>
  </dt>
    <dd id="accordian-2">
       Content goes here
    </dd>     
<dl>

Here's my code:

// Accordian
function closeAccordion() {
    $('.FrecuentlyAsked dt h1').removeClass('active');
    $('.FrecuentlyAsked dd').slideUp(300);
}

$('.FrecuentlyAsked dt h1').click( function() {
    var currentVal = $(this).attr('data-accordian-title');

    if ($(this.target).is('.active')) {
        closeAccordion();
    } else {
        closeAccordion();
        $(this).addClass('active');
        $('.FrecuentlyAsked  ' + currentVal).slideDown(300); 
        $('html,body').animate({scrollTop: $(this).offset().top}, 800);
    }
});

JS Fiddle Here

Hope you guys can help me Regards!

Upvotes: 0

Views: 209

Answers (4)

Vittal ks
Vittal ks

Reputation: 108

Update your closeAccordion() method with the code below and it will work fine

function closeAccordion() {
   $('.FrecuentlyAsked dt h1').removeClass('active');
   $('.FrecuentlyAsked dd').slideUp(0);
}

Upvotes: 1

Mayank
Mayank

Reputation: 1392

I got the Fix, try the FIDDLE,

There is too much delay used that causing the problem.

$('.FrecuentlyAsked dt h1').click(function () {
        var $this = $(this); // caching object
        var currentVal = $(this).attr('data-accordian-title');

        if ($(this.target).is('.active')) {
            closeAccordion();
        } else {
            closeAccordion();

                $(this).addClass('active');
                $('.FrecuentlyAsked  ' + currentVal).slideDown(300);
            setTimeout(function () {
                $('html,body').animate({scrollTop: $this.offset().top}, 800);


            }, 400);



        }
    });

Hope this helps..

Upvotes: 0

Phuong
Phuong

Reputation: 35

You only edit this row:

$('html,body').animate({scrollTop: $('.FrecuentlyAsked').offset().top}, 800);

And here is demo

Upvotes: 0

Vittal ks
Vittal ks

Reputation: 108

use below code $('.FrecuentlyAsked dd').slideUp(0);

Upvotes: 0

Related Questions