Header Ads

ad

Animated scroll to section Id from navigation using Jquery


Hello friends, in this blog we have come with our favourite web language that is Jquery. We will show you how to use jquery for animated scroll to target section id in our HTML pages. Let us start.

For this, we need to have some knowledge in HTML, CSS and Jquery, we assume that you all know the basic knowledge of both the languages. We will simply build a navigation menu in our pages using HTML and style them to the basic and minimum. This effect will be better for a single page application project, where all sections are present there in the page.

HTML

<!-- navigation menu -->
<ul class="navigation">
    <li><a href="#home">Home</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#product">Products</a></li>
    <li><a href="#technology">Technology</a></li>
    <li><a href="#contact">Contact</a></li>
</ul>
<!-- home section -->
<div class="site-section" id="home">
    <h1>Home section</h1>
</div>
<!-- about section -->
<div class="site-section" id="about">
    <h1>About section</h1>
</div>

<!-- product section -->
<div class="site-section" id="product">
   <h1>Product section</h1>
</div>
<!-- technology section -->
<div class="site-section" id="technology">
    <h1>Technology section</h1>
</div>
<!-- contact section -->
<div class="site-section" id="contact">
    <h1>Contact section</h1>
</div>

CSS

/* we will style the navigation menu and the sections very basic */

.navigation {
    list-style-type: none;
    padding-left: 0px;
    text-align: right;
}
.navigation li {
    display: inline-block;
    float: none;
}
.navigation li a,
.navigation li a:hover,
.navigation li a:focus,
.navigation li a:active {
    padding: 8px 12px;
    font-size: 16px;
    display: block;
    text-align: center;
    text-decoration: none;
}
.site-section {
    min-height: 250px;
    margin-bottom: 25px;
   border: 1px solid #212121;
}

JQUERY

/* scroll to specific section id on click navigation menu links */

$('.navigation li').find('a').click(function(){
   var $href = $(this).attr('href');
    var $anchor = $($href).offset();
    var $target = $anchor.top;
    /*animated scroll*/
    $('html, body').animate({ scrollTop : $target }, 800);
    return false;
});
That is it. We have successfully created animated scroll to specific target Id using jquery. Hope you like it. Please share this blog with everyone. Thanks.

No comments