DEV Community

Cover image for Modal Bootstrap; Handle Refresh Url When Close Modal Video
andysaktia
andysaktia

Posted on • Updated on

Modal Bootstrap; Handle Refresh Url When Close Modal Video

When I use the Bootstrap modal to display the video data, it works successfully, but the problem starts when I play the video, and start closing the video, it turns out that the video is still playing behind the scenes. Here are the things I did to deal with this problem.

Image description

Purpose

Create a script js that handles refresh url when the video is closed and autoplay when the modal button is pressed.

Prerequire

  • Understand usage modal with Bootstrap.
  • Javascript: useage of foreach array.

1. Modal Identification

In my case each modal has their own id so I collect them into one in array like the following.


var modals = ["#thestory", //name modal target
              "#theprophecy",
              "#theannouncement",
              "#theincarnation",
              "#promo_kka",
              "#promo_kingstone",
              "#kingstone_intro",
              "#kingstone_digital",
             ];
Enter fullscreen mode Exit fullscreen mode

2. Script Handle Loop

This looping script takes advantage of the identical parameter id in the array that step one does. And with the help of jquery we do set open and close modal respectively.

modals.forEach(myFunction);

function myFunction(item) {
   //berjalan ketika modal close agar video di reload dan tidak play ketika close
   $(item).on('hidden.bs.modal', function (e) {
    $(item + " video").attr("src", $(item + " video").attr("src"));
   });

   //berjalan ketika modal open, agar play automatis
   $(item).on("shown.bs.modal", function (e) {
    $(item + " video")[0].play();
   })
}
Enter fullscreen mode Exit fullscreen mode

DONE

ideas for the future, retrieve id with selector using class definition.

Top comments (0)