Scroll to target html

How to scroll an HTML page to a given anchor

I’d like to make the browser to scroll the page to a given anchor, just by using JavaScript. I have specified a name or id attribute in my HTML code:

I’d like to get the same effect as you’d get by navigating to http://server.com/path#anchorName . The page should be scrolled so that the anchor is near the top of the visible part of the page.

17 Answers 17

No jQuery required at all!

Note that this will only work once. Once the hash is set, the page won’t scroll to the same hash unless you change it to a dummy one then set it again.

You should not use scrollTo, because it is already used by the global window object. Also the parameter should not be named hash, because location.hash is defined, too. You may use this code: function scrollToHash(hashName) < location.hash = "#" + hashName; >

@MarkusZeller, why shouldn’t the parameter be called hash? It doesn’t collide with location, does it?

var element_to_scroll_to = document.getElementById('anchorName2'); // Or: var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0]; // Or: var element_to_scroll_to = $('.my-element-class')[0]; // Basically `element_to_scroll_to` just have to be a reference // to any DOM element present on the page // Then: element_to_scroll_to.scrollIntoView(); 

I at first thought Mandx was trolling, then I tried this and it worked. Beyond me how I never came across this method before. Mozilla Docs for this method. Also, it appears that this will be very well supported in browsers.

WARNING! This method can have problems if a div above it contains floating elements and cannot determine its size easily.

This is a clean solution, however as of now it doesn’t allow any tweaking, it does a hard scroll. There is an experimental parameter scrollIntoViewOptions that has a behavior: «smooth» option, but it is currently compatible with Firefox only.

If you think you want smooth scroll you should use document.getElementById(«xyz»).scrollIntoView(); so that the user doesn’t get forced smooth scroll if they have disabled that in browser settings. Safari doesn’t support this so it will just snap into correct position without animation. You should use this instead of scrolling to given pixel offset because this honors e.g. scroll-margin properties automatically. Reimplementing support for scroll-margin would be pretty complex.

Источник

Scroll to an element smoothly

As mentioned in the Scroll to an element post, we can scroll to given element smoothly by passing behavior: ‘smooth’ :

ele.scrollIntoView( behavior: 'smooth' >);

or applying the CSS property scroll-behavior to the target element:

Both methods aren’t supported in IE and Safari, and don’t allow to customize the animation.

This post introduces a smoothly scroll implementation which also allows us to customize the animation effect and duration. We’ll demonstrate in a popular use case that user can jump between sections by clicking associated navigation button.

Resource

The post doesn’t mention how to add a navigation fixed on the left (or right) of the page. You can see a simple way to create a fixed navigation on the CSS Layout site

The navigation consists of some a elements:

a href="#section-1" class="trigger">a>
a href="#section-2" class="trigger">a>
.

div id="section-1">. div>
div id="section-2">. div>

Clicking the link will scroll the page to a particular element that can be determined by the href attribute.

const triggers = [].slice.call(document.querySelectorAll('.trigger'));
triggers.forEach(function (ele)
ele.addEventListener('click', clickHandler);
>);

The clickHandler function handles the click event of a navigation element. It determintes the target section based on the href attribute. Notice that we will scroll to the target section ourselves, hence the default action will be ignored:

const clickHandler = function (e)  
// Prevent the default action
e.preventDefault();

// Get the `href` attribute
const href = e.target.getAttribute('href');
const id = href.substr(1);
const target = document.getElementById(id);

scrollToTarget(target);
>;

Don’t worry if you haven’t seen the scrollToTarget function. As the name implies, the function will scroll the page to given target .

Scroll to given target

It is the main part of the post. To scroll to given point, we can use window.scrollTo(0, y) where y indicates the distance from the top of the page to the target.

Good to know

It’s also possible to set behavior: ‘smooth’ :

window.scrollTo( top, left, behavior: 'smooth' >);

What we’re going to do is to move from the starting point to the ending point in given duration.

  • The starting point is the current y-axis offset, window.pageYOffset
  • The ending point is the top distance of the target. It can be retrieved as target.getBoundingClientRect().top
  • The duration is a number of milliseconds. You can change it to a configurable option, but in this post, it’s set as 800.
const duration = 800;

const scrollToTarget = function (target)
const top = target.getBoundingClientRect().top;
const startPos = window.pageYOffset;
const diff = top;

let startTime = null;
let requestId;

const loop = function (currentTime)
if (!startTime)
startTime = currentTime;
>

// Elapsed time in miliseconds
const time = currentTime - startTime;

const percent = Math.min(time / duration, 1);
window.scrollTo(0, startPos + diff * percent);

if (time duration)
// Continue moving
requestId = window.requestAnimationFrame(loop);
> else
window.cancelAnimationFrame(requestId);
>
>;
requestId = window.requestAnimationFrame(loop);
>;

As you see, we tell the browser to execute the loop function before the next paint happens. At the first time, startTime will be initialized as the current timestamp ( currentTime ).

We then calculate how many milliseconds has gone:

const time = currentTime - startTime;

Based on the elapsed time and the duration, it’s so easy to calculate the number of percentages we have been moving, and scroll to that position:

// `percent` is in the range of 0 and 1
const percent = Math.min(time / duration, 1);
window.scrollTo(0, startPos + diff * percent);

Finally, if there’s remaining time, we continue looping. Otherwise, we cancel the last request:

if (time  duration)  
// Continue moving
requestId = window.requestAnimationFrame(loop);
> else
window.cancelAnimationFrame(requestId);
>

Good practice

It’s common to think of using setTimeout() or setInterval() when we need to move between given points in the given duration. But it’s recommended to use requestAnimationFrame which gives better performance animation.

Customize the animation

Currently, we move to the target equally per millisecond. We move the same distance every milliseconds.

If you want, you can replace the current linear movement with other easing functions. Look at this website to imagine how each easing produces different animations.

The code below uses the easeInQuad animation:

const easeInQuad = function(t)  
return t * t;
>;

const loop = function(currentTime)
.
const percent = Math.min(time / duration, 1);
window.scrollTo(0, startPos + diff * easeInQuad(percent));
>);

In the following demo, try to move between sections by clicking an circle on the left.

Источник

Scroll to a specific Element Using html

That’s all fine if there is an id, a div-head or a name implanted into the page before it is sent to the browser. But if there is absolutely nothing marked for entry there, and you just want to directly refer to a specific text, can you do that? Can you trigger the browser’s search function (Ctrl+F) from outside, without user intervention?

12 Answers 12

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

You can also add in your CSS

Yes if that is what you are looking for, what Nicolas posted in response to your question. Though if you have access to PHP I’d suggest you use it. If you want to create a search query to jump to a certain element in the page you just need some small JS

You should mention whether you want it to smoothly scroll or simply jump to an element. Jumping is easy & can be done just with HTML or Javascript. The simplest is to use anchor’s. The limitation is that every element you want to scroll to has to have an id . A side effect is that #theID will be appended to the URL

You can add CSS effects to the target when the link is clicked with the CSS :target selector.

With some basic JS you can do more, namely the method scrollIntoView() . Your elements don’t need an id, though it is still easier, e.g.

Finally, if you need smooth scrolling, you should have a look at JS Smooth Scroll or this snippet for jQuery. (NB: there are probably many more).

Check the Browser compatibility table carefully before using Element.scrollIntoView() in production link

if by chance you are using angular with version > 1, see this answer for smooth scroll Angular smooth scroll

You do not need a library or jQuery for smooth scrolling. Chrome and Firefox supports scrollIntoView(< behavior: 'smooth' >) Source

Additionally, you can add html < scroll-behavior: smooth; >to your CSS to create a smooth scroll.

Year 2020. Now we have element.scrollIntoView() method to scroll to specific element.

var my_element = document.getElementById("my_element"); my_element.scrollIntoView(< behavior: "smooth", block: "start", inline: "nearest" >); 

Good thing is we can initiate this from any onclick/event and need not be limited to tag.

If you use Jquery you can add this to your javascript:

$('.smooth-goto').on('click', function() < $('html, body').animate(, 1000); return false; >); 

Also, don’t forget to add this class to your a tag too like this:

Here is a pure HTML and CSS method 🙂

html < scroll-behavior: smooth; /*Adds smooth scrolling instead of snapping to element*/ >#element < height: 100px; width: 100%; background-color: red; scroll-margin-block-start: 110px; /*Adds margin to the top of the viewport*/ scroll-margin-block-end: 110pxx; /*Adds margin to the bottom of the viewport*/ >#otherElement
Link 
Content
Where you want to scroll
Content
   
1
2
3
* nav < background: black; position: fixed; >a < color: #fff; display: inline-block; padding: 0 1em; height: 50px; >section < background: red; height: 100vh; text-align: center; font-size: 5em; >html < scroll-behavior: smooth; >#section1 < background-color:green; >#section3

I got it working by doing this, consider that top-page is the element that you want to scroll to:

document.getElementById("top-page").scrollTo(< behavior: "smooth", top: 0 >); 

Yes, you may use an anchor by specifying the id attribute of an element and then linking to it with a hash.

For example (taken from the W3 specification):

You may read more about this in Section Two. . later in the document 

Section Two

. later in the document Please refer to Section Two above for more details.

By using an href attribute inside an anchor tag you can scroll the page to a specific element using a # in front of the elements id name.

Also, here is some jQuery/JS that will accomplish putting variables into a div.

  Click here to scroll to the myContent section. 
.

Should you want to resort to using a plug-in, malihu-custom-scrollbar-plugin, could do the job. It performs an actual scroll, not just a jump. You can even specify the speed/momentum of scroll. It also lets you set up a menu (list of links to scroll to), which have their CSS changed based on whether the anchors-to-scroll-to are in viewport, and other useful features.

There are demo on the author’s site and let our company site serve as a real-world example too.

The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.

It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.

So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.

Otherwise, some users may not enjoy the smooth scrolling of your website / platform.

I can give a simpler example on how it can be applicable.

  
   

Smooth Scroll

Section 1

Click on the link to see the "smooth" scrolling effect.

Click Me to Smooth Scroll to Section 2 Below

Note: Remove the scroll-behavior property to remove smooth scrolling.

Section 2

Click Me to Smooth Scroll to Section 1 Above

Источник

Читайте также:  Отправить soap запрос java
Оцените статью