So I have 2 columns on my page. In the left column, I have 3 paragraphs. In the right column, I have 3 videos inside a sticky container.
My sticky container will remain stationary while the user scrolls but it should play a different video based on what paragraph the user is reading.
I am trying to adapt this answer but it is not working.
HTML
<div class="wrapper">
<div class="illustration">
<div class="gif-container">
<video class="gif" id="gif2" src="/GIF3.mp4" muted="muted"></video>
<video class="gif" id="gif2" src="/GIF2.mp4" muted="muted"></video>
<video class="gif" id="gif1" src="/GIF1.mp4" muted="muted"></video>
</div>
</div>
<div class="content">
<h1>Paragraph 1</h1>
<p class="par" id="par1">Lorem ipsum dolor sit amet.</p>
<h1>Paragraph 2</h1>
<p class="par" id="par2">Lorem ipsum dolor sit amet.</p>
<h1>Paragraph 3</h1>
<p class="par" id="par3">Lorem ipsum dolor sit amet.</p>
</div>
</div>
JS
jQuery(document).ready(function($){
function checkPos(){
let p = $('p');
let media = $('video');
let offset = 40;
let windowBottom = $(window).scrollTop() + $(window).height() + offset;
p.each(function(index) {
let parTop = $(this).offset().top;
if ( windowBottom > parTop ) {
media.get(index).play();
}
});
}
$(document).on('scroll', checkPos);
});
The error comes from using .each()
's index to select and play the relevant video. I get the following error: Uncaught TypeError: Cannot read property 'play' of undefined
.
However, index
is a number and when I type the index manually (0, 1 or 2), my code works.
What I am doing wrong?