Display a video modal upon page load, allowing users the option to click a button to reopen the modal

Looking for a way to make a video modal automatically open on page load and allow users to reopen it by clicking a button? Here's a snippet of code that might help you achieve that:

HTML

<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <!-- BootsTrap library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!-- jQuery library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <!-- Popper JS -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <!-- Latest compiled JavaScript -->
</script>
  </head>
  <body>
    <main class="body-flex container-fluid d-flex flex-column flex-fill">
          <div class="row flex-column flex-fill">
        <div class="col-12 col text-center flex-fill"> <!-- change btn position here in "txt-center" -->
          <h1></h1>
          <button type="button" class="btn btn-primary video-btn custombtnsize" data-toggle="modal" data-src="https://www.youtube.com/embed/ld2Vn8ouxqY" data-target="#myModal"> Ajuda </button>  <!-- Button trigger modal , you can use btn-lg to responsive large btn -->
        </div>
      </div>
    </main>

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <!-- Modal -->
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-body">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>        
            <div class="embed-responsive embed-responsive-16by9">  <!-- 16:9 aspect ratio -->
              <iframe class="embed-responsive-item" src="" id="video"  allowscriptaccess="always" allow="autoplay"></iframe>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

JS

<script>
  $(document).ready(function() { // Gets the video src from the data-src on each button
    var $videoSrc;  
    $('.video-btn').click(function() {
      $videoSrc = $(this).data( "src" );
    });
    console.log($videoSrc); // when the modal is opened autoplay it  
    $('#myModal').on('shown.bs.modal', function (e) {
      $("#video").attr('src',$videoSrc + "?autoplay=1&amp;modestbranding=1&amp;showinfo=0" );  // set the video src to autoplay and not to show related video. Youtube related video is like a box of chocolates... you never know what you're gonna get
    })
    $('#myModal').on('hide.bs.modal', function (e) { // stop playing the youtube video when I close the modal
      $("#video").attr('src',$videoSrc);     // a poor man's stop video
    }) 
  });   // document ready  
</script>

CSS

<style> 
  body {margin: 0,2rem;}
  .body-flex {
     min-height:100vh;
     display: flex;
     flex-direction: column;
  }
  .flex-fill {
     flex: 1 1 auto;
  }
  .custombtnsize {
      width: 120px !important;
      height: 50px !important;
  }
  .modal-dialog {
        max-width: 800px;
        margin:  30px auto;
    }
  .modal-body {
    position:relative;
    padding:0px;
  }
  .close {
    position:absolute;
    right:-30px;
    top:0;
    z-index:999;
    font-size:2rem;
    font-weight: normal;
    color:#fff;
    opacity:1;
  }
</style>

Answer №1

Initiate modal event upon page load:

    $(document).ready(function() { // Retrieve the video source from the data-src attribute on each button
              var $videoSrc = $('.video-btn').data( "src" );
              $('#myModal').modal();

              console.log($videoSrc); // Autoplay the video when the modal is opened
              $('#myModal').on('shown.bs.modal', function (e) {
                $("#video").attr('src',$videoSrc + "?autoplay=1&amp;modestbranding=1&amp;showinfo=0" );  // Set the video src to autoplay and hide related videos. It's like a box of chocolates...you never know what you'll get
              })
              $('#myModal').on('hide.bs.modal', function (e) { // Stop playing the YouTube video when the modal is closed
                $("#video").attr('src',$videoSrc);     // A simple way to stop the video
              }) 
            });   // Document ready 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

Tips on toggling the visibility of a div using jQuery and CSS via a toggle switch

Hey there, I need some help with toggling the opening and closing of a div when clicking on a toggle switch. $('.tog').on('click', function() { $('.cntr').show(); }); .switch { position: relative; display: inline-bloc ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Using Sinon with Ember to create a Mock Server

I am looking to test my controller by making an ajax call to my backend using Jasmine and Sinon. To fake my backend server with Sinon, I attempted the following approach: describe("fake server", function() { var server; beforeEach(function() { this ...

Difficulty building due to uppercase import in NPM dependency

While working on my Angular project, I encountered a dependency that uses Upper Camel Case import. from "./CSSToMatrix" export { parse, parseMat, toMat, getDistElementMatrix, caculateMatrixDist, getElementMatrix, createMatrix, } from "./C ...

Steer clear of changing props directly in VueJS to prevent unintended

I am working with a component that has props, and I need to change the value from false to true. However, I encountered a message in the Chrome console advising against mutating a prop directly because it will be overwritten whenever the parent component r ...

Generate a dynamic vertical line that glides smoothly over the webpage, gradually shifting from one end to the other within a set duration using javascript

I have designed a calendar timeline using html. My goal is to implement a vertical line that moves from left to right as time progresses, overlaying all other html elements. This functionality is similar to Google Calendar's way of indicating the curr ...

What steps can I take to ensure my dashboard table is dynamic, updates in real-time, and automatically reflects changes made in my MySQL database

FrontEnd Code import React, { Component, useState, useEffect } from "react"; import Navbar from "../Navbar/Navbar.js"; import BarChart from "../BarChart/BarChart"; import { Chart, Tooltip, CategoryScale, LinearScale, ...

Searchbox aligned to the right using Bootstrap

Looking to place a searchbox on the right next to another container aligned left: <div> <div class="pull-left"><span>SOME TEXT</span></div> <div class="pull-right"> <div class="row"> ...

Adjust the TextArea content according to the quantity of selections made in the listbox

If I have a listbox alongside a textarea: <textarea id="MyTextArea"></textarea> <select id="SelectList" multiple> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="me ...

Vue.js: Optimize Webpack bundle by excluding core-js

Below is the content of my vue.config.js file: module.exports = { configureWebpack: { externals: { "vue": "Vue", "core-js": "core-js", }, }, }; By using this configuration, I have successfully excluded the vue.js (Vue) library and ...

The passport local strategy functions properly when tested with Postman, but encounters a "missing credentials" error when used with axios

I am currently working on creating a login system using passport and a local strategy. Strangely, when I attempt to send the request through axios it doesn't seem to work, although it functions properly with Postman. When using axios, I receive an er ...

Is there a way to calculate the total of three input values and display it within a span using either JavaScript or jQuery?

I have a unique challenge where I need to only deal with positive values as input. var input = $('[name="1"],[name="2"],[name="3"]'), input1 = $('[name="1"]'), input2 = $('[name="2"]'), input3 = $('[name=" ...

Struggling to understand why the PHP/HTML form with a file upload field is not successfully uploading

I've been staring at this code for the past two hours and I can't seem to spot the issue. It's probably something simple, as I keep getting an undefined index error, but it's eluding me. Could you please take a look with fresh eyes? He ...

The issue with AngularJS Routing is that it fails to refresh the menu items when the URL and views are being

My current project involves implementing token-based authentication using the MEAN stack. The goal of my application is to display different menu items based on whether a user is logged in or not. When there is no token present, the menu should show option ...

The `react-hover` npm package functions flawlessly in the development environment despite being excluded from the production build

While working on my project, I decided to utilize the npm package react-hover and it's been effective during local development in dev build. However, when I execute the npm run build command to serve the production version, the components within the & ...

Fade out all the other images using jQuery

I have created a jQuery code to fade images, but when I move the mouse over them all images fade simultaneously! $(".playThumb").fadeTo("normal", 1); $(".playThumb").hover(function() { $(".playThumb").each(function() { if ( $(this) != $(this) ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

Convert this text into HTML code: "Textarea to

I have a basic <textarea> element that I want to transform links (www.google.com, msn.com, etc) and line breaks (\r\n) into HTML code. I found one library for converting links into <a hrefs>. Another library can convert line breaks i ...

Using npm webpack-mix to execute a JavaScript function stored in a separate file

Currently, I am facing a challenge with accessing a function that is defined in the table.js file from within my index.html. Here is a snippet of the code: table.js let table; function set_table(table) { this.table = table; consol ...