I'm using code found here:
https://codepad.co/snippet/CtLEQDKX
to lazy load the preview image for youtube videos within JComments. I have it working pretty good and looking like I want it to and it saves a massive amount of data from being unnecessarily downloaded, but for some reason the first video always gets skipped and left with no image and is unclickable. The rest work just as they're supposed to.
I have two sections the comments appear on, the other is a custom made profile page and is separate from JComments, and the same thing happens to the first video on the lists there as well. Any thoughts on why this is happening?
Here is js being used on site:
<script>
( function() {
var youtube = document.querySelectorAll( ".youtube" );
for (var i = 0; i < youtube.length; i++) {
var source = "https://img.youtube.com/vi/"+ youtube[i].dataset.embed +"/hqdefault.jpg";
var image = new Image();
image.src = source;
image.addEventListener( "load", function() {
youtube[ i ].appendChild( image );
}( i ) );
youtube[i].addEventListener( "click", function() {
var iframe = document.createElement( "iframe" );
iframe.setAttribute( "frameborder", "0" );
iframe.setAttribute( "allowfullscreen", "" );
iframe.setAttribute( "src", "https://www.youtube.com/embed/"+ this.dataset.embed +"?rel=0&showinfo=0&autoplay=1" );
this.innerHTML = "";
this.appendChild( iframe );
} );
};
} )();
</script>
This is what the html looks like in custom bbcode, identifier is stripped out from pattern.
Pattern:
[youtube]https://www.youtube.com/watch?v={IDENTIFIER}[/youtube]
HTML:
<center>
<div class="wrapper">
<div class="youtube" data-embed="{IDENTIFIER}">
<div class="play-button"></div>
</div></div></center>
and the profile str_replace is in 2 arrays, but looks like this
...., "https://www.youtube.com/watch?v=", "[youtube]", "[/youtube]",.....
replaced by
...., "", '<center><div class="wrapper"><div class="youtube" data-embed="', '"><div class="play-button"></div></div></div></center>',.....
Extra info J! 3.9.1 PHP 7.1.25 OS Linux I JComments 3.0.7
youtube
variable? Maybe there is some interference with your html? Please post your html so that we can have a look at the actual DOM being processed. Furthermore,source
is a single-use variable, so I recommend not declaring it (this won't fix the issue of course).youtube[i].dataset.embed
on the first iteration? Doesyoutube[0]
havedataset.embed
data?