For a smooth scroll I use this code:

$(document).ready(function() { $(".navbar-default ul li a[href^='#']").on('click', function(e) { // prevent default anchor click behavior e.preventDefault(); // animate $('html, body').animate({ scrollTop: $(this.hash).offset().top }, 400, function() { // when done, add hash to url // (default click behaviour) window.location.hash = this.hash; }); }); 

When you click on a link in the address bar, #undefined added instead of the hash value of this link.

Layout

    2 answers 2

    this inside a function that is called when the animation finishes, points to the element for which the animation was called. In this case, first in html , then in body .

    It makes sense to save a to a separate variable before invoking an animation. For example, like this: var that = this; , then use window.location.hash = that.hash;

    The final code (I removed the html from html, body , so that the function was called only once):

     $(document).ready(function() { $(".navbar-default ul li a[href^='#']").on('click', function(e) { e.preventDefault(); var that = this; $('body').animate({ scrollTop: $(this.hash).offset().top }, 400, function() { window.location.hash = that.hash; }); }); }); 

    An example in fiddle .

    • It helped, but now e.preventDefault () does not work. #Home, #about, #contact .... is added to the line. - neoman
    • @neoman in which line is added? The value in the address bar changes in the code: window.location.hash = that.hash; - Regent
    • in the address bar D: /works/web/claymore/index.html#home - neoman
    • one
      @neoman repeat: #home appears there because of the assignment in the code: window.location.hash = that.hash; . If you do not need to display an anchor in the address bar, then it is enough to delete this line. - Regent
    • wonderful thank you - neoman

    In that you are trying to take value where it is not:

     window.location.hash = this.hash; ^^^^^^^^^ 

    this in this context is just an HTML element, it does not have a hash property. You can get the address (href) of the link you clicked as follows:

     window.location.hash = $(this).attr('href'); 

    This will create a jQuery wrapper over the current element, and then get the href attribute. Remember to also replace earlier entries.

    • The phrase you are trying to take the value where it is not true, but the point is not that the DOM Element supposedly <a> does not have the .hash property, but what this indicates. - Regent
    • @Regent mda, did not know. - etki