jquerycss-selectors

need help to understand the below jquery code


<a href="#home">Home</a>
<a href="#blog">Blog</a>

<div id="home"> Volutpat wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto</div>
<div id="blog"> Volutpat wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto</div>

$('a[href*=#]').click(function(event){
            $('html, body').animate({
                scrollTop: $( $.attr(this, 'href') ).offset().top
            }, 1000);
            event.preventDefault();
        });

This code is for smooth scrolling clicking on the home,blog link. But i can't understand the jquery section. what's the meaning of this ->

$('a[href*=#]')

and this->

scrollTop: $( $.attr(this, 'href') ).offset().top

please help me. i'm a novice in jquery..


Solution

  • $('a[href*=#]') selects all a elements that have an href attribute ([] matches attributes) that contains (*= is the contains matcher) a #.

    This means the scrolling of all links that are on the same page (as they are anchor-based) is animated.


    scrollTop: $($.attr(this, 'href')).offset().top picks the offset (.offset()) to the top of the page (.top) of the target the clicked link points to ($($.attr(this, 'href))) and scrolls to this position.