Highlight html element with specific id in javascript or jquery

I have html elements with assigned id. Now I want to scroll through these elements. I see jQuery has a scrollTop that accepts an integer value. How easy is it to just create a specific html element with id scrolling at the top? Ideally, with nice and smooth animation.

A quick search revealed many scroll plugins ... if a plugin is needed for the above functions, which is the most popular? I also use jquery-ui.

+4
source share
2 answers

You can use something like this to scroll to #someElement when loading the page:

 $(document).ready(function() { $("html, body").animate({scrollTop: $("#someElement").offset().top}, 1000); }); 

It simply animates the scrollTop property of the scrollTop element and uses the top offset of some specific element as the position to scroll. Animation lasts 1000 ms.

Note: it selects both html and body , so it works in browsers. I'm not sure about the specifics, but some quick tests show that Chrome uses body , but Firefox and IE use html .

Here is a working example .

+10
source

Consider the following snippet:

 $('#myDiv').bind('click',function(){ var pos = $(this).offset().top, scrollSpeed = 2; for (var i = pos; i > 0; i=i-scrollSpeed) { $(window).scrollTop(i); } }); 

Scrolling was bound to the #myDiv element when clicked, for example. The code determines the position of the #myDiv element, which calculates the number of scroll steps (speed / smoothness). How jQuery.scrollTop () works.

0
source

Source: https://habr.com/ru/post/1369580/


All Articles