Scroll to a Specific Element Using HTML

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 do I scroll to an element using JavaScript?

You can use an anchor to "focus" the div. I.e:

<div id="myDiv"></div>

and then use the following javascript:

// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";

How to scroll to an element?

<div id="componentToScrollTo"><div>

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

This is all you need.

Scroll to an element with jQuery

Assuming you have a button with the id button, try this example:

$("#button").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});

I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$("#click").click(function (){
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
});
});
</script>
<div id="div1" style="height: 1000px; width 100px">
Test
</div>
<br/>
<div id="div2" style="height: 1000px; width 100px">
Test 2
</div>
<button id="click">Click me</button>
</html>

Javascript scroll to specific element by ID

You don't have to compute any value to do what you want, and don't have to use JavaScript at all. At least, as you don't want a smooth scrolling.

You can easily scroll to any element with it id setting the href attribute :

<a href="#my_id" id="my_link">Click me to scroll down</a>

...

<section id="my_id">...</section>

Ok, according to your comment, there is a conflict with the angular's Router when doing this, so with a little bit of JavaScript you can solve the problem :

document.getElementById("my_link").addEventListener("click",(e)=>{
e.preventDefault();
document.querySelector(e.currentTarget.href).scrollIntoView();
});

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 scroll an HTML page to a given anchor

function scrollTo(hash) {
location.hash = "#" + hash;
}

No jQuery required at all!

How to scroll to an element inside a div?

You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container):

var myElement = document.getElementById('element_within_div');
var topPos = myElement.offsetTop;

The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels).

Now we tell the div to scroll to that position using scrollTop:

document.getElementById('scrolling_div').scrollTop = topPos;

If you're using the prototype JS framework, you'd do the same thing like this:

var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];

Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).



Related Topics



Leave a reply



Submit