1

I have the following code:

<div style="overflow: scroll; width: 75px;  background-color: Black; ">
    <table style="background-color: Red">
        <tr>
            <td>
                <input type="button" id="btn1" value="1" />
            </td>
            
            <td>
                <input type="button" id="Button1" value="2" />
            </td>
            <td>
                <input type="button" id="Button2" value="3" />
            </td>
        </tr>
    </table>
</div>

Which will be disabled like the following:

enter image description here

How can I know:

  • The visible Buttons
  • The hidden Buttons (needs moving scroll to show them)
  • The offset of a Button to move the scroll to it.

Note: Recommended using JQuery.

Community
  • 1
  • 1
Homam
  • 23,263
  • 32
  • 111
  • 187

4 Answers4

1

To select the buttons, use pseudo-selectors:

$('input:button:visible')
$('input:button:hidden')

To know the offset of an element, use the .offset() method.

var offset = $('input:button').offset();

// offset.top, offset.left

Reference: .offset(), :visible, :hidden

jAndy
  • 231,737
  • 57
  • 305
  • 359
1

Try this: Check if element is visible after scrolling

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
Community
  • 1
  • 1
John K.
  • 5,426
  • 1
  • 21
  • 20
1

Compare the width()(docs) and height()(docs) of the container to the position()(docs) properties of the element, taking into consideration the scrollTop()(docs) and scrollLeft()(docs) .

var container = $('#myContainer');
var w = container.width();
var h = container.height();

var el = $('#Button1');
var pos = el.position();
var el_h = el.height();
var el_w = el.width();

container.scroll(function() {
    var st = container.scrollTop();
    var sl = container.scrollLeft();
    if ( pos.top < (h + st) && 
        (pos.top + el_h) > st && 
         pos.left < (w + sl) &&
        (pos.left + el_w) > sl ) { console.log('visible'); }
});

EDIT: Fixed it so that it is not considered visible when the scrolling exceeds the element in either direction.

user113716
  • 318,772
  • 63
  • 451
  • 440
0

With jQuery, you can use the position() function for each button to check which ones are after 75px on the left - that would mean hidden by the scroll. position() is what you need, and not offset(), as you want to know the position within the DIV container, not in the whole document.
BTW, if you're using a table just to have your buttons on the same line, I'd suggest to put them directly in the DIV, space separated, and to add white-space:nowrap in the style.

Nabab
  • 2,608
  • 1
  • 19
  • 32