简体   繁体   中英

How to scroll to top of page when accordion is clicked?

I have the following jQuery, its working fine. What I need is when the accordion is clicked to take the user to the top of page of the active accordion.

Here is the code:

jQuery(document).ready(function($){

    $('.accordion-container').hide();

    //$('.accordion-toggle:first').addClass('active').next().show();

    $('.accordion-toggle').click(function(){
        if( $(this).next().not(':hidden') ) {
            $('.accordion-toggle').removeClass('active').next().slideUp();

        }
        if( $(this).next().is(':hidden') ) {

            $('.accordion-toggle').removeClass('active').next().slideUp();

            $(this).toggleClass('active').next().slideDown();

        }

        return false; // Prevent the browser jump to the link anchor

    });    
});

Thank you in advance :)

You can use plain javascript to scroll the page programmatically:

window.scrollTo(0, 0);

Here's what your code should look like:

jQuery(document).ready(function($){

    $('.accordion-container').hide();

    //$('.accordion-toggle:first').addClass('active').next().show();

    $('.accordion-toggle').click(function(){

        if( $(this).next().not(':hidden') ) {
            $('.accordion-toggle').removeClass('active').next().slideUp();

        }

        if( $(this).next().is(':hidden') ) {

            $('.accordion-toggle').removeClass('active').next().slideUp();

            $(this).toggleClass('active').next().slideDown();

        }

        //scroll to top
        window.scrollTo(0, 0);

        return false; // Prevent the browser jump to the link anchor

    });    

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM