Display a pop-up video player when a button is clicked to watch multiple videos on a webpage utilizing jQuery/Javascript

I am in need of assistance with integrating multiple embedded YouTube videos (using iframes) that appear on the screen after a user clicks a custom button.

While there are solutions available for single videos, I am struggling to make it work for multiple videos on the same page.

The button is located within a series of uniform div elements across all the videos. Once the video pops up, clicking outside of it should close the modal.

The following code aims to identify the parent element after the button click and open the corresponding video modal, but unfortunately, nothing happens as expected.

Any guidance or support provided would be highly appreciated!

Answer №1

Initially, the modal and trailerbox variables are not properly defined. Since they are descendants of a sibling element of the button, using .closest() will not locate them.

For each element in the set, find the first element that matches the specified selector by iterating through the element itself and its ancestors in the DOM hierarchy.

As it checks itself first, followed by the parent elements, these entities will not be discovered. To locate them, you should utilize .find() starting from the parent element.

var modal = $(this).closest('.card').find('.trailerdivbox');

Take a look at this example:

$(function() {
  function openVideo(event) {
    var card = $(this).closest(".card");
    var modal = $(".trailerdivbox", card);
    modal.addClass("isOpen").show();
  }

  function closeVideo(event) {
    var modal = $(".trailerdivbox.isOpen");
    modal.removeClass("isOpen").hide();
  }
  
  $(".videos").on("click", ".watchbutton", openVideo);
  $(".videos").on("click", ".close", closeVideo);
  
});
/* Watch Trailer Button CSS */

.watchbutton {
  background-color: #f2f2f2;
  color: red;
  font-weight: 600;
  border: none;
  padding: 10px 12px;
}

.watchbutton:hover {
  background-color: #e2e2e2;
  cursor: pointer;
}

.trailerdivbox {
  display: none;
  width: 100%;
  height: 100%;
  position: fixed;
  overflow: auto;
  /* Enable Scrolling */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

.videoWrapper {
  position: relative;
  padding-bottom: 56.25%;
  /* 16:9 */
  padding-top: 25px;
  height: 0;
}

.videoWrapper iframe {
  position: absolute;
  max-width: 560px;
  max-height: 315px;
  width: 95%;
  height: 95%;
  left: 0;
  right: 0;
  margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='videos'>
  <div class='card'>
    <button class="watchbutton">Watch Trailer &#9658</button>
    <div class="close">
      <div class="trailerdivbox">
        <div class="videoWrapper">
          <iframe class="trailervideo" width="560" height="315" src="https://www.youtube.com/embed/TDwJDRbSYbw" frameborder="0" allowfullscreen>
          </iframe>
        </div>
      </div>
    </div>
  </div>
  <div class='card'>
    <button class="watchbutton">Watch Trailer &#9658</button>
    <div class="close">
      <div class="trailerdivbox">
        <div class="videoWrapper">
          <iframe class="trailervideo" width="560" height="315" src="https://www.youtube.com/embed/TDwJDRbSYbw" frameborder="0" allowfullscreen>
          </iframe>
        </div>
      </div>
    </div>
  </div>
</div>

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

Incorporate smooth transitions into isotope elements

I am currently working on implementing transitions to div elements within an isotope (v2) list. Specifically: .isotope-item { width: 340px; height: 223px; border: 10px solid black; background-color: #000; -webkit-transition: background-color 0.25s linear, ...

Adjusting Grid Posts to a Consistent Size (Featuring Photo Posts with Captions Below)

I'm attempting to adjust the size of posts in grid mode on Tumblr. I've discovered that I can modify the width of each post using CSS. However, I'm struggling to locate where I can set the height of a grid post to a specific size. For inst ...

JavaScript: Finding the full Base-URL - A Step-by-Step Guide

Is there a way to incorporate JavaScript into external files without relying on the use of base/root URLs in HTML/PHP templates? Everything is functioning properly except for the need to determine the base/root URL in an included JS file. Dilemma: I am se ...

Repositioning with Flexbox: shifting the middle element to a new line

I have a flex item that contains three divs. ┌────────────────────────────────────────┐ | WRAPPER | | ┌─────────┬─ ...

What are the steps for retrieving a JSON object within an array?

var jsonData = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue" :{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text" :"Size32","price":"22","isSelec ...

Querying form data in a POST request using node.js and express

I am working on a basic node.js app and I need to retrieve the post body from the user. app.js var express = require('express'); var app = express(); app.use(express.json()); app.post('/api/user', function (req, res) { console.lo ...

Which is the more appropriate option to use in JavaScript: "this" or "event.target"?

Take a look at the simple demonstration below. It showcases a div element that will disappear when clicked. <div id="three" onclick="toggle2(event);return false;" style="background:#303; color:#FFF;"> function toggle2(e) { var textx = (e.targe ...

Challenge with unstable video streaming from blob in Angular 7

Currently, I am in the process of developing an offline application that incorporates a stored video within indexeddb. To achieve this, I am creating a URL from the blob that is being stored: const videoBlob = await this.storage.get<Blob>('some ...

Having trouble getting rounded-lg and rounded-md to work properly with Tailwind CSS - any ideas why?

I'm currently working with Next.js version 14.2.4 and tailwindcss version 3.4.1, and I've encountered an issue where rounded-lg and rounded-md classes are not applying any border radius. Oddly enough, other classes like rounded-xl and just rounde ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

bootstrap class not detected and not visible in Firebug

I have been delving into a book about bootstrap in order to master it. Upon downloading the bootstrap files and integrating them into my test file, test.html, I encountered an issue where the "navbar-toggle" class was not recognized by my browser and did n ...

Guide to implementing a slider in HTML to adjust the size of my canvas brush

Hey there, I'm looking to implement a slider functionality under my canvas that would allow users to change the brush size. Unfortunately, all my attempts so far have been unsuccessful. Can anyone lend a hand? Much appreciated! <canvas i ...

Which data type should I utilize to transfer an array of integers using ajax?

[HttpDelete] public JsonResult ReservationCancel(int[] reservationId) { var model = ReservationDAO.getReservation(reservationId); return Json(model,JsonRequestBehavior.AllowGet); } I have a list of Ids (1, 2, 3, 4, 5, 6, 7) that I want to delete a ...

Creating Responsive Images with Bootstrap at Specific Breakpoints

As a newcomer to Bootstrap, I am embarking on my first website creation experience. The header of my site is designed to look like the image below: https://i.sstatic.net/WTp2g.jpg I want this image to adjust responsively on medium-sized and larger device ...

Having trouble with @font-face not displaying in my style.css file

I've been scouring the internet in search of an answer to this dilemma, yet my quest has proved futile. Within my style.css file, I've utilized @font-face to incorporate a font (which I previously uploaded to my website's server) on my site. ...

Tips for enlarging an image by tapping on it in handlebars

I currently have the handlebars template engine integrated with node.js, and I'm facing an issue where thumbnail images from the database are displaying at a fixed width and height of 70. Is there a way to enable users to click on these images in orde ...

Centering Image and Media Body in Bootstrap's Media Object

Welcome to my first post on stackoverflow, hoping everything goes smoothly. I am struggling with aligning the content centrally and placing the images to the left and right of the center in 3 media objects. I have provided images of the current layout and ...

Sending information through a form in html to a server via AngularJS Http Post

Seeking assistance with a posting issue related to an AngularJS form. Despite using ng-submit and ng-click for the function, it's not functioning as expected. Can anyone offer guidance? <form method="post" class="sky-form" name="form"> < ...

"Attempting to update the view by calling a controller function from a directive proves ineffective

I'm in the process of developing an application where an Ajax request is made to fetch a list of packages from the server and then display them. Additionally, I've created a directive named "packageDetails" that is applied to each individual pack ...

What is the best way to selectively delete elements in d3.js?

I am faced with the task of manipulating a graph. I begin by opening and processing a file to extract the necessary modifications for the graph. These modifications are essentially node names stored within the text field of each node. My challenge lies in ...