Scroll Smoothly to Specific Element on Page

Scroll smoothly to specific element on page

Just made this javascript only solution below.

Simple usage:

EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);

Engine object (you can fiddle with filter, fps values):

/**
*
* Created by Borbás Geri on 12/17/13
* Copyright (c) 2013 eppz! development, LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/

var EPPZScrollTo =
{
/**
* Helpers.
*/
documentVerticalScrollPosition: function()
{
if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
return 0; // None of the above.
},

viewportHeight: function()
{ return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },

documentHeight: function()
{ return (document.height !== undefined) ? document.height : document.body.offsetHeight; },

documentMaximumScrollPosition: function()
{ return this.documentHeight() - this.viewportHeight(); },

elementVerticalClientPositionById: function(id)
{
var element = document.getElementById(id);
var rectangle = element.getBoundingClientRect();
return rectangle.top;
},

/**
* Animation tick.
*/
scrollVerticalTickToPosition: function(currentPosition, targetPosition)
{
var filter = 0.2;
var fps = 60;
var difference = parseFloat(targetPosition) - parseFloat(currentPosition);

// Snap, then stop if arrived.
var arrived = (Math.abs(difference) <= 0.5);
if (arrived)
{
// Apply target.
scrollTo(0.0, targetPosition);
return;
}

// Filtered position.
currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);

// Apply target.
scrollTo(0.0, Math.round(currentPosition));

// Schedule next tick.
setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
},

/**
* For public use.
*
* @param id The id of the element to scroll to.
* @param padding Top padding to apply above element.
*/
scrollVerticalToElementById: function(id, padding)
{
var element = document.getElementById(id);
if (element == null)
{
console.warn('Cannot find element with id \''+id+'\'.');
return;
}

var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
var currentPosition = this.documentVerticalScrollPosition();

// Clamp.
var maximumScrollPosition = this.documentMaximumScrollPosition();
if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;

// Start animation.
this.scrollVerticalTickToPosition(currentPosition, targetPosition);
}
};

How to navigate to another page with a smooth scroll on a specific id?

Modern Browsers detect the hash in the url and then automatically open that part. So, if you want to scroll smoothly to that part instead, you first need to reset the scroll position to 0 and then add smooth scrolling.

Add the following script

// direct browser to top right away
if (window.location.hash)
scroll(0,0);
// takes care of some browsers issue
setTimeout(function(){scroll(0,0);},1);

Now, try to access the anchor from other page and you will notice that the browser takes you to top of the page without scrolling to the anchor element.

Now, add smooth scroll:

$(function(){
//your current click function
$('.scroll').on('click',function(e){
e.preventDefault();
$('html,body').animate({
scrollTop:$($(this).attr('href')).offset().top + 'px'
},1000,'swing');
});

// if we have anchor on the url (calling from other page)
if(window.location.hash){
// smooth scroll to the anchor id
$('html,body').animate({
scrollTop:$(window.location.hash).offset().top + 'px'
},1000,'swing');
}
});

It will work perfectly now. You will be taken to the anchor element in other page with scrolling smoothly to that part.

Complete code:

// direct browser to top right away
if (window.location.hash)
scroll(0,0);
// takes care of some browsers issue
setTimeout(function(){scroll(0,0);},1);

$(function(){
//your current click function
$('.scroll').on('click',function(e){
e.preventDefault();
$('html,body').animate({
scrollTop:$($(this).attr('href')).offset().top + 'px'
},1000,'swing');
});

// if we have anchor on the url (calling from other page)
if(window.location.hash){
// smooth scroll to the anchor id
$('html,body').animate({
scrollTop:$(window.location.hash).offset().top + 'px'
},1000,'swing');
}
});

Smooth scroll to specific div on click in css

Actually, it is even commented in the CSS of your linked code:

/*
*Scrolling
*/

a[ id= "servicios" ]:target ~ #main article.panel {
-webkit-transform: translateY( 0px);
transform: translateY( 0px );
}

a[ id= "galeria" ]:target ~ #main article.panel {
-webkit-transform: translateY( -500px );
transform: translateY( -500px );
}
a[ id= "contacto" ]:target ~ #main article.panel {
-webkit-transform: translateY( -1000px );
transform: translateY( -1000px );
}

Add to this the fact that panel class has the following:

.panel {
[...]
-webkit-transition: -webkit-transform 0.6s ease-in-out;
transition: transform 0.6s ease-in-out;
[...]
}

This makes it move smoothly instead of instantly.

/* Button */    .button {        background: #ffff00;        color: #000;        border-radius: 4px;        border: 0;        display: inline-block;        font-weight: 700;        height: 2.95em;        line-height: 3em;        padding: 0 1.5em;        text-decoration: none;        text-align: center;        margin-top: 1em;    }    #descr {        display: flex;        height: 90vh;    }    #descr .desc {        padding: 3.5em 0 1.5em 0;        padding-left: 2em;        padding-right: 2em;        background: #afdeed;        width: 50%;    }    .image.desc img {        text-align: center;        box-shadow: 5px 5px 20px;    }    .image.desc img {        animation: move 2s ease-in-out infinite;        animation-direction: alternate-reverse;    }    @-webkit-keyframes move {        0% {            transform: translate(0);        }        100% {            transform: translate(2.5em);        }    }    .image.desc:hover img {        animation: rotate 2s ease-in-out infinite;        animation-direction: alternate-reverse;    }
@-webkit-keyframes rotate { 0% { transform: translate(-5em); } 25% { transform: rotate(20deg); } 50% { transform: translate(5em); } 75% { transform: rotate(-20deg); } } /* *Scrolling */
.panel { width: 100%; height: 500px; z-index:0; -webkit-transform: translateZ( 0 ); transform: translateZ( 0 ); -webkit-transition: -webkit-transform 0.6s ease-in-out; transition: transform 0.6s ease-in-out; -webkit-backface-visibility: hidden; backface-visibility: hidden;
}
a[ id= "descLink" ]:target ~ #description section.panel { -webkit-transform: translateY( -100px); transform: translateY( -100px );}
<html><head></head>  <a id="descLink"/>  <ul class="actions">      <li><a href="#descLink" class="button" id="cn">Continue</a></li>  </ul>        <section id="description">            <h2 style="font-weight: 700; font-size: 1.5em; margin-top: 2em;">Description</h2>            <section id="descr" class="panel">                    <div class="image desc"><img src="https://cdn.lynda.com/course/439683/439683-636441077028502313-16x9.jpg" width="800" height="550" title="Our company">                    </div>                    <div class="desc">                        <h2>About Company</h2>                        <p>Sometimes the mouse, but now it was the makeup of chocolate sauce ante powerful protein manufacturing sad sauce through a gateway.</p>                    </div>            </section>        </section></html>

Smooth scroll to specific div on click

do:

$("button").click(function() {
$('html,body').animate({
scrollTop: $(".second").offset().top},
'slow');
});

Updated Jsfiddle

Scroll to a specific Element Using html

Yes you use this

<a href="#google"></a>

<div id="google"></div>

But this does not create a smooth scroll just so you know.

You can also add in your CSS

html {
scroll-behavior: smooth;
}

How to scroll to an element?

<div id="componentToScrollTo"><div>

<a href='#componentToScrollTo'>click me to scroll to this</a>


Related Topics



Leave a reply



Submit