Mathieu Préaud
Mathieu Préaud

Reputation: 423

Dynamic click function with auto generate IDs

I have the following html code which is generated automatically by a shortcode in Wordpress. It consists to add dynamically a video (from Youtube) in the front end. My idea is to have multiples videos on the same page. Each time the user add a shortcode it will create the html.

<div class="row entry-video">
  <div class="video-container">
    <div class="video-cover" style="background-image:url('img/cover-video.jpg');"></div>
    <iframe class="video-iframe" width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>
  </div>
</div>

To make the design a bit more attractive, the user can add his own cover over the video (class video-cover). So when you click the image, the cover disappears and autoplays the video.

My issue is, by the fact the code is added dynamically by shortcode and there are multiples videos on the page, I can't success to make the click action (to remove the image and play for each video) working properly.

The JS code to auto add an ID to each video entry:

$('.entry-video').each(function(i) {
  $(this).attr('id', 'video-' + (i + 1));
}); 

The JS code to remove the cover and play the video:

$('.video-cover').on('click',function(e){
  $(this).fadeOut(400);
  $('.video-iframe')[0].src += "?autoplay=1";
  e.preventDefault();
});

The click function works fine if there is only one video. Both scripts are working but they are not related one the other. Things get more complicated if there are more videos. So what I would like to do is to create a dynamic function that generates and auto detects the ID of the cover which has been clicked in relation with the ID of the iframe played.

Any help would be much appreciated, thanks!

Upvotes: 2

Views: 281

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337646

Generating id attributes at runtime is an anti-pattern, don't do that.

Instead, use the common classes on the elements to genericise the logic by traversing the DOM from the element which raised the click event to find those related to it. Using this pattern means that a single event handler will work for an infinite number of elements.

In your case you can achieve this by using the next() method, as the target element is a sibling of the .video-cover which raises the event. Try this:

$('.video-cover').on('click', function(e) {
  e.preventDefault();
  $(this).fadeOut(400).next('.video-frame').prop('src', (i, src) => src += '?autoplay=1');

  // alternative:
  // $(this).fadeOut(400).next('.video-frame')[0].src += '?autoplay=1';
});

Upvotes: 3

Related Questions