user007
user007

Reputation: 3243

jQuery smooth scroll, do only if anchor link is an id

I have written a smooth scroll function using jQuery. But there is a problem,

if anchor has only hash in href, then it return undefined error. like:

<a href="#" title="something">Link</a>

Please tell how to run my function only if anchor link is an ID and not if only hash.

Here is my function:

//smooth scroll

jQuery('a[href^="#"]').click(function (e) {    
        e.preventDefault();
        var target = this.hash;
        jQuery('html, body').animate({ 
                  scrollTop: (jQuery(target).offset().top) - 60 
                }, 1000);    
});

Upvotes: 0

Views: 5068

Answers (4)

DazChong
DazChong

Reputation: 3562

just to share my single line minimal solution:

$('a[href^="#"]').click(function(e){e.preventDefault();var o=$(this.hash).offset();if(o)$('body').animate({scrollTop:o.top})})

only tested on chrome

Upvotes: 0

user007
user007

Reputation: 3243

I got the small solution for the problem, simply check if target is undefined, if yes then don't run it.

Here is my code

//smooth scroll
jQuery('a[href^="#"]').click(function (e) {
    e.preventDefault();
    var target = this.hash;

    if (typeof(jQuery(target).offset()) != 'undefined') {
        jQuery('html, body').animate({
            scrollTop: jQuery(target).offset().top - 60
        }, 1000);
    }
});

Upvotes: 0

Eli
Eli

Reputation: 14827

You can try to do:

jQuery('a').each( function() {
    var $this = jQuery(this), 
        target = this.hash;
    jQuery(this).click(function (e) { 
        e.preventDefault();
        if( $this.length > 0 ) {
            if($this.attr('href') == '#' ) {
                // Do nothing   
            } else {
               jQuery('html, body').animate({ 
                    scrollTop: (jQuery(target).offset().top) - 60 
                }, 1000);
            }  
        }
    });
});  

You should give your desired anchors a specific class instead of targeting every anchors like above.

Upvotes: 3

palaѕн
palaѕн

Reputation: 73926

Try this:

jQuery('a').click(function (e) {
    e.preventDefault();
    var target = this.hash;
    if (this.href != '#') {
        jQuery('html, body').animate({
            scrollTop: jQuery(target).offset().top - 60
        }, 1000);
    }
});

Upvotes: 4

Related Questions