How do I know if any content is in the visible area of ​​a div that has a scroll bar? JQuery

I have a table with rows. The table is in a div. A table is taller than a div, and so the div has a vertical scroll bar, and some rows in the table are in the invisible area of ​​the div. Things are good.

Then, through JavaScript, I look for some text that tells me which line it is on. If this line is not visible, I want to scroll through the div to show this line.

How to determine if this line is in the visible or hidden part of the div? Perhaps I will get it from a height calculation, but wondered if there is a simpler method.

+4
source share
2 answers

Using jQuery, use the position () function to get the position of the corresponding row, then set this value to ScrollTop () to jump to the element.

Here's how to do it.

var item = $('#test').position().top; $('button').click(function() { $(window).scrollTop(item) }) 

Check out the working example http://jsfiddle.net/U6tsg/1/

I also created an animated version

 var item = $('#test').position().top; $('button').click(function() { $('html, body').animate({ scrollTop: item }, 'slow'); }); 

Check out the working example at http://jsfiddle.net/U6tsg/2/

+3
source

There is a DOM method called .scrollIntoView() that does exactly what you are describing. Here's how to use it:

 var tr = document.getElementById("myRow"); tr.scrollIntoView(); 

The method has the optional argument alignWithTop , which not only guarantees the visibility of the element, but also places the element at the top of the alignWithTop viewport (just like clicking on an anchor, as the Shadow Wizard suggests in its comment)

+5
source

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


All Articles