简体   繁体   中英

jQuery combine 2 scripts to achieve smooth scrolling to anchor

I have the following jquery function which shows / hides content depending on the div that is selected...

jQuery(document).ready(function() {
  jQuery('.showSingle').on('click', function () {
    jQuery(this).addClass('selected').siblings().removeClass('selected');
    jQuery('.targetDiv').hide();
    var selector = '#div' + jQuery(this).data('target');
    jQuery(selector).show();
    location.hash = selector;
  });
});

http://jsfiddle.net/W4Km8/7944/

I also have the following script taken from http://1stwebmagazine.com/jquery-scroll-to-anchor-point

$(document).ready(function(){
    $('a[href^="#"]').bind('click.smoothscroll',function (e) {
        e.preventDefault();

        var target = this.hash,
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top-40
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

I am trying to combine the 2 so that instead of jumping to the anchor it scrolls to it. Do I need to combine them or can they be made to work separate?

Looks like you can combine them easily enough, I've made it work with this jsfiddle: http://jsfiddle.net/9soxbhpj/

var target = jQuery(selector);
target.show()
$('html, body').stop().animate({
        'scrollTop': target.offset().top-40
    }, 900, 'swing', function () {
        window.location.hash = selector;
    });

You can add the scroll action in the same click call. See the js:

jQuery(document).ready(function() {

  jQuery('.showSingle').on('click', function () {
    var _el = jQuery(this),
        _target =  jQuery('#div' + _el.data('target')),
        _targetDiv = jQuery('.targetDiv');

    _el.addClass('selected').siblings().removeClass('selected');
    _targetDiv.hide();
    _target.show();

    // Scroll to object
    $('html, body').animate({
        scrollTop: _target.offset().top
    }, 800);

  });

});

Here is a working example .

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