public9nf
public9nf

Reputation: 1399

jQuery scrollTop event is not animating

I need jQuery animate together with scrollTop to create a smooth scroll effect to my anchor links. In my current project this is not working. All the animate - scrollTop Events are doing nothing. I load jQuery 3.1.1 in the header. In my footer main.js i use the the following javascript:

$('a[href*=#]').on('click', function(event){    
    console.log("ScrollTop");
    $("html, body").animate({ scrollTop: 500 }, "slow");
    return false;
}); 

I can see the ScrollTop in my Console but there is no animation. I dont know what to do i tried a lot of things. I also tested it in all the different browsers its working nowthere.

Upvotes: 0

Views: 102

Answers (2)

DinoMyte
DinoMyte

Reputation: 8858

The issue is that your selector with href contains # gives a different meaning without the quotes. Once you put # in quotes, it works fine.

$('a[href*="#"]').on('click', function(){  
    $('html,body').animate({scrollTop: 500}, "slow");    
});

Example : https://jsfiddle.net/3vy7adh7/

Or

If you want to avoid the post on any valid a tag,

$('a').on('click', function(e)
{    
    e.preventDefault();
    if($(this).attr('href').indexOf('#') > -1)
      $('html,body').animate({scrollTop: 500},"slow");     
});

Example : https://jsfiddle.net/3vy7adh7/1/

Upvotes: 1

Action Coding
Action Coding

Reputation: 830

This should work for you:

    $('a[href^="#"]').on('click',function (e) {
        var href = $(this).attr('href');
        e.preventDefault();
        var target = this.hash,
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top - 180
        }, 900, 'swing', function () {
            window.location.hash = target;          
        });
    });

Upvotes: 0

Related Questions