Ben
Ben

Reputation: 35

JS/jQuery – Check initial position once inside a loop (scroll event)

EDIT

var setInitPos = true;

function loop() {

  $(".image").each(function() {
    // some other code

    if (imageIsVisible) {
      // some other code

      // Set variable initPos only once for each item
      if (setInitPos) {
        initPos = $(window).scrollTop();
        setInitPos = false;
      }
    }

    // some other code
  })

}

$(window).scroll(function(){ loop() }

If an item is visible within the viewport fill the var initPos once with a value for each item.

But now the second item starts with setInitPos = false! Why is that?

Upvotes: 0

Views: 96

Answers (3)

Adam Jenkins
Adam Jenkins

Reputation: 55762

EDIT

The best way to persist initPos on a per DOM-element basis is by attaching it to each DOM element, which you can do with jQuery's .data()

  $(".image").each(function() {
    var initPos = $(this).data('initpos') || 0;

    // some other code

    if (imageIsVisible) {
      // some other code

      // Set variable initPos only once for each item
      if (!initPos) {
        $(this).data('initpos',$(window).scrollTop());
      }
    }

Upvotes: 0

Bálint
Bálint

Reputation: 4049

It's global, because you specified it in the global scope.

To make it local to the iteration, then declare it within the function. You need to use the varbkeyword for this (or let if you use ES6)

To make it local to the image, use this.initPos, this way you create a new attribute for each image element.

Upvotes: 1

GitzJoey
GitzJoey

Reputation: 65

i found no other variable declared except initPos. And Its only declared once.

try to declare "var initPos" again inside "if (imageIsVisible) {"

Upvotes: 0

Related Questions