JSFiddle - React, Tailwind, and code Playground

by Noir Noir

HTML

<section style="height:100px"><p>1</p> </section>
<section style="height:150px"><p>2</p> </section>
<section style="height:300px"><p>3</p> </section>
<section style="height:200px"><p>4</p> </section>
<section style="height:100px"><p>5</p> </section>
<section style="height:200px"><p>6</p> </section>
<section style="height:300px"><p>7</p> </section>
<section style="height:400px"><p>8</p> </section>
<section style="height:100px"><p>9</p> </section>
<section style="height:130px"><p>10</p> </section>
<section style="height:150px"><p>11</p> </section>
<section style="height:400px"><p>12</p> </section>

CSS

section {
  background: #ddd;
  margin: 20px 0
}

JavaScript

// Получаем нужный элемент
var elements = document.querySelectorAll('section'),
		viewTimeouts = {},
    secondsLimit = 4,
    viewPercentLimit = 80;

var Visible = function (target) {

    // Все позиции элемента
    var targetPosition = {
            top: window.pageYOffset + target.getBoundingClientRect().top,
            bottom: window.pageYOffset + target.getBoundingClientRect().bottom
        },
        // Получаем позиции окна
        windowPosition = {
            top: window.pageYOffset,
            bottom: window.pageYOffset + document.documentElement.clientHeight
        };

    if (targetPosition.bottom > windowPosition.top && // Если позиция нижней части элемента больше позиции верхней чайти окна, то элемент виден сверху
        targetPosition.top < windowPosition.bottom) { // Если позиция верхней части элемента меньше позиции нижней чайти окна, то элемент виден снизу
        // Если элемент полностью видно, то запускаем следующий код
        // console.log('element', target.textContent, 'is visible');
        var targetSize = targetPosition.bottom - targetPosition.top,
        		targetVisibleTop = targetPosition.top > windowPosition.top ? targetPosition.top : windowPosition.top,
            targetVisibleBottom = targetPosition.bottom < windowPosition.bottom ? targetPosition.bottom : windowPosition.bottom,
            viewSize = targetVisibleBottom - targetVisibleTop,
        		percent = 100 * viewSize / targetSize;
        return percent > viewPercentLimit;
    } else {
        // Если элемент не видно, то запускаем этот код
        
    };

};

var VisibleElements = function(elements){
	for(var i=0; i<elements.length; i++) {
  	var element = elements[i];
    if(!element.dataset['id']) {
    	element.dataset['id'] = genElementId();
    }
    var elementId = element.dataset['id'],
    		isVisible = Visible(element);
    if (isVisible) {
    	// console.log('element', element.textContent, 'is visible');
    	if (!viewTimeouts[elementId]) {
      	//...