user4739890
user4739890

Reputation:

Using prototype with scrollTop to make instances of a Class(js class) active (css class)

I think the title is pretty confused, but i dont know how to named what i'm trying to do.

I have a paragraph:

<p data-initial="100" data-final="1000">Test</p>

NOTE THE DATA-*

And this paragraph have a simple CSS:

p {
  color: black;
  margin-top: 500px;
}
p.active {
  color: red;
}

And this paragraph is an instance of Animation class:

+ function($) {
  var Animation = function(element) {
    this.element = $(element);
    this.initial = this.element.data('initial');
    this.final = this.element.data('final');

    if (this.initial > $(this).scrollTop()) {
      this.applyAnimation();
    }
  }

  Animation.prototype.applyAnimation = function() {
    alert('WORKED!!');
    this.element.addClass('active');
  }

  Animation.prototype.disableAnimation = function() {
    this.element.removeClass('active');
  }

  $(window).on('load', function() {
    $('[data-initial]').each(function() {
      var animation = $(this);
      animation = new Animation(this);
    });
  });


}(jQuery);

With this code, i'm trying to apply the .active class in the paragraph if the page scroll more them 100, but is not working at all, not happens.

I think maybe it's because I'm trying to 'hear' the scroll inside the prototype , it is not possible? How can I make my instance hear the scroll and apply the class when the page scroll over 100 ??

If i do this:

  $(window).scroll(function() {
    if ($(this).scrollTop() > 100) {
      console.log('test');
    }
  });

The test will appear in my console, so, the window.scroll code is not wrong.

Upvotes: 0

Views: 150

Answers (1)

CodingWithSpike
CodingWithSpike

Reputation: 43728

I think this line might cause a problem:

if (this.initial > $(this).scrollTop()) {

"this" will be the new instance of Animation which isn't an element. Maybe that should be this.element.scrollTop()?

Upvotes: 1

Related Questions