FORSMILE
JA
JavaScript2020/12/22

Execute Code When an Element Becomes Visible [jQuery]

With jQuery, you can add events that trigger when an element becomes visible within the viewport.

Back to Blog

With jQuery, you can add events that trigger when an element becomes visible within the viewport.

JQUERY PLUGIN: JQUERY.INVIEW

javascript
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="../jquery.inview.min.js" />

・・・

// code
$(function() {
  $('.inview').on('inview', function(event, isInView) {
    if (isInView) {
        // element is now visible in the viewport
    } else {
        // element has gone out of viewport
    }
  });
});

In the example above, an event is triggered when an element with the class `inview` becomes visible on the screen. You can also write it more concisely like this:

javascript
$('.inview').on('inview', function(){
        $(this).addClass('active');
});

The example above adds the `active` class to the element once it appears.

This is a useful feature with various applications, such as triggering animations when an element becomes visible.

RECOMMENDED JQUERY BOOKS

Many jQuery books tend to be outdated. However, jQuery itself is still actively evolving.

📦
Amazon で関連書籍・ツールを検索
JavaScript programming book
Amazonで探す →(アソシエイトリンク)