开发者

How to scroll the page to specific tag or class on slideToggle and on callback to scroll it to another tag or class?

Here is my code:

$(".trigger").click(function ()开发者_开发百科 {
    $('.toggleContainer').slideToggle();
    $('.trigger').text($(this).text() == 'Show more' ? 'Hide' : 'Show more');
    $('.trigger').toggleClass('trigger_alt')
    $('html, body').animate({
        scrollTop: $(".trigger").offset().top
    }, 800);
});

How can i scroll back to another tag on the page or in my case to another class which is above the .trigger class... lets say to my .header for example on slideToggle callback (when you click to close toggle back the toggleContainer). I know that this second scroll should be in the callback, but if i do it this way:

    $('html, body').animate({
        scrollTop: $(".trigger").offset().top
    }, 800, function () {
        $('html, body').animate({
            scrollTop: $(".header").offset().top
        }, 800);

    });

it animates to .trigger and without stopping animates to .header


The second animation should not be in the callback. If you're using the click event for the open and close functions you'll have to use some method to check the state of the toggle and then do one animation or the other, not both. The other option is to split the entire function into two separate functions and use the toggle event rather than the click event on the .trigger element.


var trigger = $('.trigger');
var container = $('.container');
trigger.toggle(

function () {
    container.slideDown();
    trigger.text($(this).text() == 'Learn more' ? 'Hide' : 'Learn more');
    $('html, body').animate({
        scrollTop: $(".trigger").offset().top
    }, 800);
}, function () {
    container.slideUp();
    trigger.text($(this).text() == 'Learn more' ? 'Hide' : 'Learn more');
    $('html, body').animate({
        scrollTop: $(".header").offset().top - 20
    }, 800);
});

Ok i answered my question. If someone have better solution, post it here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜