Perform function when closing modal in Vue

Asked

Viewed 674 times

1

I’m using Bootstrap 4 in a project with Vue;

In modal, I have a video on a Youtube iframe;

What I need to do is pause this video, when I close the modal, either by pressing the key Esc, or closing in the x modal or clicking outside the modal to close it.

Does anyone have any idea what function I can perform to pause this video?

Note: I am not using jQuery.

Edit: This modal is inside a Vue component, so I believe that jQuery will not work.

Follows code:

Modal:

<!-- Modal Vídeo-->
          <div class="modal fade" id="ModalVideo" tabindex="-1" role="dialog" aria-labelledby="ModalVideoLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
              <div class="modal-content content_modal">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
                <div class="corpo_video">
                  <iframe width="100%" height="450px"
                    :src="'https://www.youtube.com/embed/'+texto[0].video">
                  </iframe>
                </div>
              </div>
            </div>
          </div>

Knob:

<div class="company__box pop" data-toggle="modal" data-target="#ModalVideo">
 <span>
  Assista ao nosso
   vídeo institucional
   </span>
</div>
  • Wouldn’t it just be adding a click function on the close button? Type @click="minhaFuncaoPause()"

  • Use the API of Youtube, otherwise you will not be able to control the player within an iframe.

  • Example: https://jsfiddle.net/3s1jwx5g/

  • I don’t understand how you’re using BS4 without jQuery.

1 answer

1


You can stop video via Javascript using the method .postMessage(). To do this add the parameter ?enablejsapi=1 in the src of the video:

:src="'https://www.youtube.com/embed/'+texto[0].video+'?enablejsapi=1'"

Create a function that will be called when the modal is closed by the event hide.bs.modal. The function will contain the method that will make the video pause:

function paraVideo(){
   document.querySelector('.modal-body iframe')
   .contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}

The value in func pauseVideo makes the video pause. If you want to do the video stop swap for stopVideo.

You call the function by the event when the modal closes:

$('#ModalVideo').on('hide.bs.modal', paraVideo);

See on JSFIDDLE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.