0

I have this piece of code, which displays ALL the elements with the same class whenever the first one appears on the screen. What I really wanted to do is to show each element separately whenever it appears on the screen, not all of them in the same time. I hope I explained it clear enough.

Here is the html:

  <div class="scrollfx">ELEMENT</div>    
  <div class="scrollfx">ELEMENT</div>

css:

body {
  height:1600px;
}

.scrollfx {

  width: 100%;
  height: 150px;
  background:blue;
  position: relative;
  top: 50px;
  font-size:4em;
  margin-top:500px;    
  filter: opacity(0);
}
.scrollfx.fadein {
  filter:opacity(1);
  transition: all 2.5s ease;
}

jquery:

$(document).scroll(function () {

  var el = $('.scrollfx');
  var bottom = el.offset().top + el.outerHeight(true);
  var y = $(this).scrollTop();

  $('.scrollfx').each(function () {
    if (y = bottom) {
      $(this).addClass('fadein'); 
    }           
  });

});

Jsfiddle here

Piotr Ciszewski
  • 1,691
  • 4
  • 30
  • 53
  • `var bottom = el.offset().top + el.outerHeight(true);` will give you only one value (of the first element in collection) - you can always debug your code using `console.log()`, remember? Therefore the logical way would be to get that value inside the `.each()` - for each element. Makes sense? – Roko C. Buljan Feb 18 '18 at 17:57
  • thanks, but I'm not very good in javascript, therefore I need to work on this a bit. I thought it may be a an easy solution to simply add a line or two to the code. – Piotr Ciszewski Feb 18 '18 at 17:59
  • No, you have all the code you need, just, you need to move your variables inside the each function, and instead of using `el` use `$(this)` – Roko C. Buljan Feb 18 '18 at 18:00
  • also `=` is a setter. And `y` should be placed outside of the `.each()` - before it. – Roko C. Buljan Feb 18 '18 at 18:04
  • 2
    See this Answer: https://stackoverflow.com/a/27462500/383904 – Roko C. Buljan Feb 18 '18 at 18:05
  • Also be aware that with your approach, `scrollTop` of the document will never reach the same value as the bottom of the last element in the document - unless the viewport has a height of `0` maybe. – Arsylum Feb 18 '18 at 18:08

0 Answers0