简体   繁体   中英

jQuery - Using .slideToggle and .animate simultaneously

I have a portion of jQuery that just doesn't seem to be working correctly. I have a link to click, [show/hide] which should slideToggle a div. At the same time, I want to animate it so that the page scrolls to the top of the div. It works when I put the animate function inside the slideToggle function, like in this jfiddle .

However, this means that the div i want slides out, and then the page scrolls down. id like to set it up so that both happen simultatneously, which I tried to do in this jfiddle but it simply doesn't work. I also tried doing the scroll animation first, then the slideToggle, which didn't work - is there a way to implement this also?? Cheers!

$(document).ready(function () {
    $('.click_to_hide').click(function () {
        var visible = $('.hide_on_click').is(":visible");
        $('.hide_on_click').slideToggle(500);
        if (!visible) {
            $('html, body').animate({
                scrollTop: $('.hide_on_click').offset().top
            }, 500);
        }
    });
});

http://fiddle.jshell.net/YFR2e/3/

$(document).ready(function () {
    $('.click_to_hide').click(function () {
        $('.hide_on_click').slideToggle(500);
        if($('.hide_on_click').is(':visible')){
          $('html, body').animate({
                scrollTop: $('.hide_on_click').offset().top
            }, 500);
        }
    });
});

try to put it in the same function

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