Florian Müller
Florian Müller

Reputation: 3

Exclude specific # from scrollTo Animation in jquery

the jquery code below let me scroll to a link like #link inside my page. But now I have a three special links, #tab-1 #tab-2 #tab-3 that shall not be included in this scrollto script, just do nothing. I can't figure out how to exclude specific # from this script.

Thank you for your help!

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

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

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top-80 //offset -80 for navigation height
    }, 900, 'swing');
});

Upvotes: 0

Views: 132

Answers (3)

Joe
Joe

Reputation: 15528

I would change your code to this:

var special = ['#tab-1', '#tab-2', '#tab-3'];

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

    var target = this.hash;

    if( $.inArray( target, special ) > -1 ) return;

    var $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top-80
    }, 900, 'swing');
});

This defines an array of 'special' values that the hash can't equal. $.inArray() is used to check whether the current hash matches one of the values in the special array. If it does then it returns and the code below isn't executed.

Another example for carousel in Bootstrap :

var special = ['#carousel-example-generic'];
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash;
    if( $.inArray( target, special ) > -1 ) return;
    var $target = $(target);

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

Upvotes: 1

Florian Müller
Florian Müller

Reputation: 3

Thank you all! It was clearly to late yesterday for me :) Joe's answer works great with any given #parameter I include in the var special list. So its perfect for dynamic templates too.

Thanks again!

Upvotes: 0

Fergoso
Fergoso

Reputation: 1582

try:

var special = ['#tab-1', '#tab-2', '#tab-3'];

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

    var target = this.hash;
    var $target = $(target);
    if( $.inArray( target, special ) > -1 ){
       $('html, body').stop().animate({
        'scrollTop': $target.offset().top-80 //offset -80 for navigation height
       }, 900, 'swing');
    }
});

Upvotes: 0

Related Questions