Search code examples
javascriptjqueryjquery-waypoints

How do I grab the ID of $this using jQuery and Waypoints


I'm trying to grab the ID of a waypoint element and then add that ID value as a class to the body when scrolling reaches that waypoint. This doesn't seem to work though.

HTML

<body class="bg-1">
<div id="content">
    <div class="cover">
        <h2>Title</h2>
        <p class="keep-scrolling">Keep scrolling along</p>
    </div>
    <section class="stats">
        <article id="bg-1">
            /* stuff */
        </article>
        <article id="bg-2">
            /* stuff */
        </article>
        <article id="bg-3">
            /* stuff */
        </article>
        <article id="bg-4">
            /* stuff */
        </article>
    </section>
</div>
</body>

Javascript

$(function() {
  $("article").waypoint(function(direction) {  //callback when waypoint is reached, with direction of scroll as a parameter
    var $this = $(this); // caching the waypoint element

    if($this.attr("id") == "bg-1") {
      $("body").removeClass();
      $("body").addClass('bg-1');
    } else if($this.attr("id") == "bg-2") {
      $("body").removeClass();
      $("body").addClass("bg-2");
    } else if($this.attr("id") == "bg-3") {
      $("body").removeClass();
      $("body").addClass("bg-3");
    } else if($this.attr("id") == "bg-4") {
      $("body").removeClass();
      $("body").addClass("bg-4");
    } else {
      $("body").addClass("bg-1");
    };

  });
});

I've a number of way to grab the ID, but can't get the syntax right.


Solution

  • You are using the callback-function of waypoint wrong.

    Refering to the API this should be working for you:

    $(function() {
      $("article").waypoint({
        handler: function(direction) {
          $("body").removeClass(function(index, css) {
            return (css.match(/(^|\s)bg-\S+/g) || []).join(' ');
          });
          //or $("body").removeClass();
          $("body").addClass(this.element.id);
        }
      });
    });
    

    I tweaked your solution a bit more:

    • Remove all classes from body starting with bg- (see this answer for reference)
    • add the id as class (removed unnecessary ´if´ construct)

    Example