eloism eloism - 1 month ago 8
jQuery Question

Targeting the first and last non-overflowing elements

In order to return the number of items overflowing to the right and to the left, I am looking for a way to target the first and last elements which are not overflowing (so i can count after and before them).



.container {
overflow: hidden;
width: 430px;
display: flex;
border: 2px solid green;
}

.inner {
height: 100px;
width: auto;
display: flex;
align-items: center;
justify-content: center;
position: relative;
right: 145px
}

a {
display: inline-flex;
align-items: center;
justify-content: center;
width: 50px;
height: 50px;
border: 1px solid grey;
margin: 0 10px;
}

<div class="container">
<div class="inner">
<a>1</a>
<a>2</a>
<a>3</a>
<a>4</a>
<a>5</a>
<a>6</a>
<a>7</a>
<a>8</a>
<a>9</a>
<a>10</a>
<a>11</a>
<a>12</a>
<a>13</a>
<a>14</a>
</div>
</div>





In this exemple how would I target the first and last not overflowing elements (in this case 3 and 8) ?

I tried things like
$('.inner a:visible').last()
or
$('.inner a:visible:last')
but it wouldn't work.

Thanks !

Answer Source

You can use offset() and then filter() out elements that are less then 0 and larger that width of parent and take first and last element.

var c = $('.container');
var cl = c.offset().left;

$('a').filter(function() {
  var xl = $(this).offset().left
  return (cl - xl) < 0
}).first().css('background', 'red')

$('a').filter(function() {
  var xl = $(this).offset().left
  return xl < (cl + c.width())
}).last().css('background', 'red')
.container {
  overflow: hidden;
  width: 430px;
  display: flex;
  border: 2px solid green;
  margin-left: 100px;
}

.inner {
  height: 100px;
  width: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  right: 145px;
}

a {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border: 1px solid grey;
  margin: 0 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="inner">
    <a>1</a>
    <a>2</a>
    <a>3</a>
    <a>4</a>
    <a>5</a>
    <a>6</a>
    <a>7</a>
    <a>8</a>
    <a>9</a>
    <a>10</a>
    <a>11</a>
    <a>12</a>
    <a>13</a>
    <a>14</a>
  </div>
</div>