DEV Community

Kay Gosho
Kay Gosho

Posted on

Fade in Image without jQuery

I don't know how many people have wrote this kind of articles, but wrote fade in image or text without jQuery.

.fadein {
  opacity: 0;
}
.fadein.is-active {
  opacity: 1;
  transition: all ease 0.65s;
}
Enter fullscreen mode Exit fullscreen mode
// Fade in Threshold
const screenOffset = window.innerHeight / 2 

const elements = document.getElementsByClassName('fadein')
for (let element of elements) {
  window.addEventListener('scroll', () => {
    if (window.scrollY + screenOffset > element.offsetTop) {
      element.classList.add('is-active')
    }
  })
}
Enter fullscreen mode Exit fullscreen mode
  <p style="height: 100vh">Prints out this usage information.</p>
  <img class="fadein" src="https://www.google.co.jp/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">
Enter fullscreen mode Exit fullscreen mode

If you use React, you should write the above code in componentDidMount.

Ref:

http://brian.hatenablog.jp/entry/floating-fade-in

Top comments (3)

Collapse
 
equinusocio profile image
Mattia Astorino • Edited

You should use data attributes to show Ui state changes

Collapse
 
acro5piano profile image
Kay Gosho • Edited

Thank you for your comment.
Did you mean attribute like <img src="..." data-active />?
I will try it though I actually do not know the advantage.

Collapse
 
equinusocio profile image
Mattia Astorino

Because you can make it readable by accesibility technologies