thumbtackthief
thumbtackthief

Reputation: 6211

Trigger a waypoint when halfway through a div

I have a div containing a long, multi-screen blog post. The length varies depending on the content. I'd like to trigger a waypoint when a third of the way through the div. I understand the offset function, but that seems to apply to how far down the screen the div appears. I don't have the ability to modify the HTML to include any identifier; I would need to do it through the Javascript entirely.

$('.article-body').waypoint({
  handler: function() {
    alert('Hit midpoint of my context');
  },
  context: ".article-body",
  offset: $(".article-body").height * 0.33
});

Sample HTML:

<body>
    <div class="article-body">
        CONTENT CONTENT CONTENT
    </div>
<body>

Upvotes: 2

Views: 1896

Answers (2)

imakewebthings
imakewebthings

Reputation: 3398

I see Daniel's answer has been accepted, but here's how to do it with Waypoints: An offset function that returns a negative number.

Offsets are always in terms of distance from the top of the element to the top of the window. Let's say we have a 300px tall element. If we set the offset to -100 that would have the effect of triggering when the top third of the element is scrolled past. Now let's make that a dynamic function:

offset: function() {
  return this.element.offsetHeight / -3;
}

Upvotes: 3

Daniel Beck
Daniel Beck

Reputation: 21485

This is sloppy with global variables, but you'll get the idea; the gist of it is to determine ahead of time where you want your "waypoint" triggered, then watch window scrolling until it reaches that point.

(Note that if your content changes after page load you'll need to recalculate waypointPos. You could calculate it on the fly every time, but the scroll event fires frequently enough that that might cause lagginess; I'd poll the window scroll position on a slower interval rather than do DOM calculations constantly during window scroll.)

// determine the scroll position where we want to do something, which is the element's top offset plus half of its height:
var waypointPos = ($('.hasWaypoint').height() / 2) + $('.hasWaypoint').offset().top;

// watch window scroll until we search that point:
var waypointTriggered = false;
$(window).scroll(function() {
  if (!waypointTriggered && $(window).scrollTop() >= waypointPos) {
    alert("Halfway there!");
    waypointTriggered = true; // don't keep triggering endlessly
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="height:200px">This is extra stuff whose height we want to ignore</p>
<div class="hasWaypoint" style="height: 3000px;border:1px solid">This is the big div</div>

Upvotes: 1

Related Questions