Advertisement
salmancreation

detect when an element is fully visible then do whatever

Dec 24th, 2023
1,362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 0.96 KB | None | 0 0
  1. This is what I use to detect when an element is fully visible then do whatever I want with it:
  2.  
  3. // Create jQuery Method
  4. jQuery.fn.isFullyVisible = function(){
  5.  
  6. var win = $(window);
  7.  
  8. var viewport = {
  9.     top : win.scrollTop(),
  10.     left : win.scrollLeft()
  11. };
  12. viewport.right = viewport.left + win.width();
  13. viewport.bottom = viewport.top + win.height();
  14.  
  15. var elemtHeight = this.height();// Get the full height of current element
  16. elemtHeight = Math.round(elemtHeight);// Round it to a whole number
  17.  
  18. var bounds = this.offset();// Coordinates of current element
  19. bounds.top = bounds.top + elemtHeight;
  20. bounds.right = bounds.left + this.outerWidth();
  21. bounds.bottom = bounds.top + this.outerHeight();
  22.  
  23. return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
  24.  
  25. }
  26.  
  27. //Usage:
  28. $(window).on('scroll', function() {
  29.   if( $('.tailor .content').isFullyVisible() ){
  30.     // do something
  31.   }
  32. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement