Skip to content
Advertisement

How to get .load() working within .each() loop?

I’m modifying a bit of code I found here from this question. I am trying to get it working now for multiple instances of a video. This is the only way I can get it working but I would like to make it work for each instance that there is a video which changes on each page this applies on.

$( function() {
  const bgv = $('.bgvid');
  $('source', bgv).each(function() {
    const el = $(this);
    el.attr('src', el.data('src'));
  });
  bgv[0].load();
  bgv[1].load();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<video class="bgvid" playsinline="playsinline" loop="loop" autoplay="autoplay" muted="muted" preload="none">
  <source type="video/mp4" data-src="https://archive.org/download/UNIVAC-AD-2/UNIVAC2_512kb.mp4">
</video>
<video class="bgvid" playsinline="playsinline" loop="loop" autoplay="autoplay" muted="muted" preload="none">
  <source type="video/mp4" data-src="https://archive.org/download/UNIVAC-AD-2/UNIVAC2_512kb.mp4">
</video>

I have tried putting it within a loop like this instead of the bgv[0].load(); but it didn’t work:

$('.bgvid').each(function(){ 
$(this).load();
});

Advertisement

Answer

Just call this.load(), don’t convert the DOM element into a jQuery element.

$( function() {
  const bgv = $('.bgvid');
  $('source', bgv).each(function() {
    const el = $(this);
    el.attr('src', el.data('src'));
  });

  bgv.each(function() {
    this.load();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<video class="bgvid" playsinline="playsinline" loop="loop" autoplay="autoplay" muted="muted" preload="none">
  <source type="video/mp4" data-src="https://archive.org/download/UNIVAC-AD-2/UNIVAC2_512kb.mp4">
</video>
<video class="bgvid" playsinline="playsinline" loop="loop" autoplay="autoplay" muted="muted" preload="none">
  <source type="video/mp4" data-src="https://archive.org/download/UNIVAC-AD-2/UNIVAC2_512kb.mp4">
</video>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement