Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading