Search code examples
jqueryhtmlscrollpositioncursor

How can I get selected div on scroll?


I have a div contains lots of cells with random height. The aim is : "the user stop the scroll to choose a cell, all cells can be chosen". A cell is selected/chosen by a cursor at the left top corner. The cursor change of cell when user scroll the div. I have made a demo, but the problem is when user is at the bottom, the N last cells can't be selected by cursor. How can I do this please ?

Thank you for help :)

$(document).ready(function() {
  for (i = 0; i < 100; i++) {
    var h = Math.floor(Math.random() * (50 + 1) + 20);
    $('.content').append('<div id="' + i + '" class="cell" style="height:' + h + 'px;"></div>');
  }
  
  $(document).on('scroll', function() {
    var id = current();
    $('.cursor').css('top', $('#' + id).position().top + 'px')
  });
});

function current() {
  $('.cell').each(function() {
    if ($(this).position().top > $(document).scrollTop()) {
      id = $(this).attr('id');
      return false;
    }
  });
  return id;
}
.cell {
  width: 100px;
  border: 1px solid;
  margin-bottom: 5px;
}

.cursor {
  width: 0px;
  height: 0px;
  z-index: 9999;
  position: absolute;
  border-style: solid;
  border-width: 10px 10px 0px 0px;
  border-color: #000 transparent transparent transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <div class="cursor"></div>
</div>

https://codepen.io/lokomass/pen/OJyXXwV


Solution

  • It is because your event is based on scroll and at the end when the scroll stops it cannot decide which element to give cursor on so just add the following css in your code to increase the space at the bottom of the content to keep on scrolling till the last element.

    .content {
      margin-bottom : 130px;
    }
    
    

    Or just make the last parameter as 65.

     var h = Math.floor(Math.random() * (50 + 1) + 65);
    
    

    Note: It atleat require 65 to get to the last one.