1

I have a bootstrap 3 columns youtube videos

<div class="col-md-4">
  <div class="video_img_wrapper">
    <img class="video_img" data-toggle="modal" class="ytVideo" id="'.$item->id->videoId.'" data-target="#myModal_'.$item->id->videoId.'" src="'.$thumbnailUrl.'" />
    <img src="'.get_bloginfo('template_url').'/assets/img/playicon-nl.png" class="fa-play-circle-o" aria-hidden="true" data-toggle="modal" data-target="#myModal_'.$item->id->videoId.'" />
  </div>
  <div class="video_title"><span>'. $item->snippet->title .'</span></div>
</div>

<div class="modal fade youtube-modal" id="myModal_'.$item->id->videoId.'" role="dialog">
  <div class="modal-dialog">
    <div class="modal-body" id="videoModalBody"></div>
  </div>
</div>

And I am injecting an iframe using jquery in the #videoModalBody div

$(".video_img").click(function(evt){
  var videoId = $(this).attr("id");
  var iframe = '<iframe enablejsapi=1 id="myModal_'+videoId+'" width="850" height="500" src="https://www.youtube.com/embed/'+videoId+'" frameborder="0" allowfullscreen></iframe>';
  $("#videoModalBody").append(iframe);
});

How can I change my Javascript so when I click on another video the previous one gets removed out of the DOM?

2 Answers 2

1

You can set a global class on iframe then remove all iframe before append new one:

$('.globalIframe').remove();
$("#videoModalBody").append(iframe);

$(".video_img").click(function(evt) {
  var videoId = $(this).attr("id");
  var iframe = '<iframe enablejsapi=1 id="myModal_' + videoId + '" class="globalIframe" width="850" height="500" src="https://www.youtube.com/embed/' + videoId + '" frameborder="0" allowfullscreen></iframe>';
  $('.globalIframe').remove();
  $("#videoModalBody").append(iframe);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="video_img">Click Me</a>
<div id="videoModalBody"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

You can reference it by class name or store a reference in a variable, IE:

var videoId = null; // Shared reference
$(".video_img").click(function(evt){
    if (videoId) $('#'+videoId).remove(); //remove previous videos if present
    videoId = $(this).attr("id"); //store new id
    var iframe = '<iframe enablejsapi=1 id="myModal_'+videoId+'" width="850" height="500" src="https://www.youtube.com/embed/'+videoId+'" frameborder="0" allowfullscreen></iframe>';
              $("#videoModalBody").append(iframe);
          });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.