Home > Software engineering >  on scroll once element is in view - detach event from element but not from rest
on scroll once element is in view - detach event from element but not from rest

Time:08-12

I get "e is not defined" error, and if I set the e on the scroll it works for the first element but then it's detached for the rest. What I'm trying to do is - once the element is in view the first time, to detach the event to stop it from firing on each scroll movement.

($.fn.isInViewport = function() {
    var a = $(this).offset().top,
      c = a   $(this).outerHeight(),
      b = $(window).scrollTop(),
      d = b   $(window).height();
    return c > b && a < d;
  });

  $(window).scroll(function() {
    if ($('.title1').isInViewport(e)) {
      console.log('title1');
      $(this).off(e);
    } else if ($('.title2').isInViewport(e)) {
      console.log('title2');
      $(this).off(e);
    } else if ($('.title2').isInViewport(e)) {
      console.log('title2');
      $(this).off(e);
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<h2 >Title1</h2>
<div style="height: 600px;"></div>
<h2 >Title2</h2>
<div style="height: 600px;"></div>
<h2 >Title3</h2>


CodePudding user response:

You are not assigning an event handler. You are just testing the position of the element on the window scroll event. So you just have to STOP showing it

($.fn.isInViewport = function() {
  var a = $(this).offset().top,
    c = a   $(this).outerHeight(),
    b = $(window).scrollTop(),
    d = b   $(window).height();
  return c > b && a < d;
});

const classesToMonitor = [".title1","title2","title3"];
const len = classesToMonitor.length;
classesToMonitor.forEach(cls => $(cls).data("monitor",true));
let stopped = 0;
$(window).scroll(function() {
  if (stopped === len) return;  // don't even test
  $('.title1, title2, .title3').each(function() { // we could even splice the array
    if ($this().isInViewport() && $(this).data("monitor")) {
      console.log($(this).attr("class"))
      $(this).data("monitor",false);
      stopped  ;
    }
  })
});
  • Related