When the mouse hovers over a div a video will play. Everything works fine but the video only plays on the first “player”. I can see the thumbnail on every player but they don’t start to play. Why is this happening?
<?php foreach($posts as $post) { $vimeoid = get_field('film_vimeo', $post, true); if (empty($vimeoid)) { $projektclass = "not-vimeo"; } else { $projektclass = "vimeo"; } //echo '<div id="hp-post"><a href="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</a></div>'; echo '<div class="'.$projektclass.'" style="position: relative;" id="hp-post">'; echo get_the_post_thumbnail( $post, 'full' ); echo '<div id="'.$vimeoid.'"><iframe class="vimeoplayer" id="'.$vimeoid.'" style="position: absolute; z-index:-1;" src="https://player.vimeo.com/video/'.$vimeoid.'?title=0&byline=0&portrait=0&background=1&autoplay=0 width="100%" height="0" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div></div>'; } echo '</div>'; } ?>
jQuery(document).ready(function() { var vimeo = document.getElementsByClassName('vimeo')[0]; var player = new Vimeo.Player(vimeo); vimeo.onmouseover = function() { return player.play(); }; vimeo.onmouseout = function() { return player.pause(); }; });
Advertisement
Answer
The issue is because you only retrieve the first item in the collection of elements (ie. the [0]
item) and bind events to that. None of the other elements are affected. To fix this you need to loop through them.
I would also suggest using addEventListener()
for this instead of the onX
event properties. Try this:
jQuery($ => { Array.from(document.getElementsByClassName('vimeo')).forEach(el => { let player = new Vimeo.Player(el); el.addEventListener('mouseover', () => player.play()); el.addEventListener('mouseout', () => player.pause()); }); });