The issue at hand is that one of the JavaScript buttons is functioning properly, while the other is not playing the video as intended. What steps can

I've been working on a script for my school project website that should make buttons play videos, but I'm running into an issue where it only works for the first button (btn). Programming isn't my strong suit, and I put this together based on tutorials. I just need it for one school assignment. Can someone please help me understand and fix the problem?

const btn = document.querySelector('.btn');
const videoContainer = document.querySelector('.video-containere');
const close = document.querySelector('.close');

btn.addEventListener('click', () => {
  videoContainer.classList.add('show');
})
close.addEventListener('click', () => {
  videoContainer.classList.remove('show');
})
const btn2 = document.querySelector('.btn2');
const videoContainer2 = document.querySelector('.video-container2');
const close2 = document.querySelector('.close'); //changed variable name to avoid conflict

btn2.addEventListener('click', () => {
  videoContainer2.classList.add('show');
})
close2.addEventListener('click', () => {
  videoContainer2.classList.remove('show');
})
.btn {
  text-decoration: none;
  padding: 15px 40px;
  background-color: #fff;
  color: #000000;
  border-radius: 40px;
  font-family: 'Century Gothic';
  font-weight: bolder;
}

.video-containere {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 99999;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s;
}

.video-containere .close {
  position: absolute;
  top: 10px;
  right: 25px;
  font-size: 20px;
  cursor: pointer;
}

.video-containere video {
  width: 90%;
  max-width: 800px;
  transform: scale(0);
  box-shadow: 0 20px 20px rgba(0, 0, 0, 0.2);
  outline: none;
  transition: all 0.3s;
}

.video-containe...

<div class="content active">
  <h1>Cristiano Ronaldo</h1>
  <p>Cristiano Ronaldo ist ein portugiesischer Fußballspieler, der seit Ende August 2021 zum zweiten Mal in seiner Karriere bei Manchester United unter Vertrag steht. </p>
  <a href="#" class="btn"> Mehr... </a>
</div>

<div class="content">
  <h1>Muhammad Ali</h1>
  <p>Muhammad Ali war ein US-amerikanischer Boxer und der einzige, der den Titel des unumstrittenen Weltmeisters dreimal in seiner Karriere gewinnen konnte. Bekannt wurde er zunächst unter seinem Namen Cassius Clay. Er gehörte zu den bedeutenden Schwergewichtsboxern
    und herausragenden Sportathleten des 20. </p>
  <a href="#" class="btn2"> Mehr... </a>
</div>

<div class="modal">
  <div class="video-containere">
    <span class="close"> &#10006; </span>
    <video src="CENSORED cause of private website" muted controls> </video>
  </div>
</div>

<div class="modal">
  <div class="video-container2">
    <span class="close"> &#10006; </span>
    <video src="CENSORED cause of private website" muted controls> </video>
  </div>
</div>

Answer №1

It is important to assign tasks to others

I have relocated the display to a modal and included data attributes in the links to direct to the relevant video. You might consider changing the video source and utilizing just one modal

document.getElementById('container').addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.matches(".btn")) {
    document.getElementById(tgt.dataset.id).classList.add("show")
  } else if (tgt.matches(".close")) {
    tgt.closest(".modal").classList.remove("show")
  }
})
.btn {
  text-decoration: none;
  padding: 15px 40px;
  background-color: #fff;
  color: #000000;
  border-radius: 40px;
  font-family: 'Century Gothic';
  font-weight: bolder;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 99999;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s;
}

.modal .close {
  position: absolute;
  top: 10px;
  right: 25px;
  font-size: 20px;
  cursor: pointer;
}

.modal video {
  width: 90%;
  max-width: 800px;
  transform: scale(0);
  box-shadow: 0 20px 20px rgba(0, 0, 0, 0.2);
  outline: none;
  transition: all 0.3s;
}

.modal.show {
  pointer-events: all;
  opacity: 1;
}

.modal.show video {
  transform: scale(1);
}

.btn {
  text-decoration: none;
  padding: 15px 40px;
  background-color: rgb(255, 122, 0);
  color: #fff;
  border-radius: 40px;
  font-family: 'Century Gothic';
  font-weight: bolder;
  box-shadow: 0 10px 40px rgba(255, 122, 0, 0.4);
}
<div id="container">
  <div class="content active">
    <h1>Cristiano Ronaldo</h1>
    <p>Cristiano Ronaldo is a Portuguese footballer, who since late August 2021 has been under contract with Manchester United for the second time in his career. </p>
    <a href="#" class="btn" data-id="vid1"> More... </a>
  </div>

  <div class="content">
    <h1>Muhammad Ali</h1>
    <p>Muhammad Ali was a US boxer and the only one who could win the title of undisputed world champion three times in his career. Initially known as Cassius Clay, he was one of the significant heavyweight boxers
      and outstanding athletes of the 20th century. </p>
    <a href="#" class="btn" data-id="vid2"> More... </a>
  </div>

  <div class="modal" id="vid1">
    <div class="video-container">
      <span class="close"> ✖ </span>
      <video src="CENSORED cause of private website" muted controls> </video>
    </div>
  </div>

  <div class="modal" id="vid2">
    <div class="video-container2">
      <span class="close"> ✖ </span>
      <video src="CENSORED cause of private website" muted controls> </video>
    </div>
  </div>
</div>

Answer №2

When using window.querySelector(), only the first matched element in the dom tree is selected. Consider using window.querySelectorAll() or a different selector to capture multiple elements

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

Contents of the container are not displayed in a single line

What could be causing the first element not to align with the other elements in the container? I'm having trouble figuring out why this is happening. The code snippet seems to work, but when I implement it on the webpage, the alignment issue arises. W ...

The min-width of 100vh is functioning properly on mobile devices, however, it is not working as expected on PCs when set to 100

When using 100vh, it only works on mobile or if you narrow the width of your web browser on a PC. If the window/width is set at 100%, the image may appear too tall and cause the div class "mars" to overflow the viewport. Unfortunately, screenshots cannot ...

Trouble sliding with Material UI Slider

I've encountered an issue with my Material UI slider - it doesn't slide when clicked and dragged. I followed one of the examples on the Material UI website (https://material-ui.com/components/slider/) and included an onChange function. The values ...

Having trouble activating the Invalidate Cache function in rtk query with tags

Here is a snippet from my Api.js file: export const api = createApi({ reducerPath: 'api', baseQuery: fetchBaseQuery({ prepareHeaders: (headers, { getState }) => { const userInfo=JSON.parse(localStorage.getItem('userInfo' ...

What is the best way to split text copied from a textarea into <p> paragraphs with an equal number of characters in each?

Check out this JSFiddle version I've found a JSFiddle example that seems perfect for my current project needs. However, I'm wondering how to modify the code to ensure that each paragraph is evenly divided with the same number of characters and a ...

How to automatically refresh a page when the URL changes with Next.js router?

On my page, users have the option to narrow down their search using filters. However, there is an issue where if a user selects a filter for "rent" or "buy", the URL does not automatically refresh to reflect the changes. Even though the changes are reflect ...

Using Firebase with Arrays in Javascript

Currently, my team and I are working on a project using Firebase with Vue.js as the framework. We've come across a challenge regarding creating, updating, and deleting elements in a Firebase cloud document. For instance, within our 'people&apos ...

Creating dynamic DIVs that adjust fluidly to different screen

I have a section containing 4 centered divs. Here is what I want to achieve: When the screen width is over 1280px, display all 4 divs in a row. When the screen width is less than 1280px, show 2 divs per row. And when the screen width is under 640px, disp ...

Combining Multiple 3D JSON Objects in JavaScript [or jQuery]

Looking to combine multiple JSON objects into one? I have a code snippet that you can use! Here is the code: http://jsfiddle.net/5Uz27/ The issue with this code is that it only merges objects on the first level, causing deeper levels to be overwritten. T ...

The conflict name has an impact on both the folder and the PHP file

Within my web directory, there exists a folder titled area-nursing that houses various PHP files along with a specific file named area_nursing.php. However, upon attempting to rewrite area_nursing.php as area-nursing using the .htaccess file, I encounter ...

Looking to extract the hidden value from an HTML input field using Selenium

Unable to retrieve the value of a hidden element in HTML, even though it is displaying. Seeking assistance in accessing the value despite the type being hidden. <input type="HIDDEN" label_value="Sub Reference" title="Sub Reference" id="ACC_NO" dbt="BK_ ...

Error Alert: Attempting to access the 'prototype' property of an undefined value has resulted in a TypeError after switching to react-scripts version 4.0.3

I encountered a problem where I received the following error message: (Uncaught Error: Module build failed (from ./node_modules/source-map-loader/dist/cjs.js)). After attempting to resolve it by using npm install, a new error popped up in the console: path ...

What is the process for activating a script file once I have replaced HTML content using a backend method?

After receiving HTML content from the backend, including the <script> tags, I noticed that the scripts.js file does not seem to be activated. While the HTML content displays fine, changing the path to style.css successfully alters the appearance of ...

What is the best way to bring JavaScript code from one component to another in React?

I am currently working on a mini shop app using VueJS without a backend, focusing on adding items to the shopping cart only. Within Component One (Nmdgrey.vue), I have boots along with an "Add to Cart" button. <button @click="addToCart">Add to cart ...

Show different values in Array arranged in Table format with the help of Ajax code

Check out the code I have attempted below: <script type="text/javascript"> $('#doctorselected').on('change', function(e){ console.log(e); var doctorid = e.target.value; var url = '{{URL::to('getdoc ...

Utilizing ElementRef in Angular 4 to close dropdown when clicking outside of it

I recently came across this helpful tutorial, but I'm having trouble grasping how it actually functions. Here's the code snippet I've incorporated into my TypeScript file: @Component({ host: { '(document:click)': 'onOuts ...

I'm having trouble grasping the concept of this asynchronous behavior

After reviewing the output provided, my initial expectation was for working to be displayed between the lines of begin and end. Here is the rule: Is there a possible solution to achieve this outcome without modifying the app.js file? app.js const se ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...

The connection timed out when attempting to send a POST request from the client side to the API

After setting up a basic https response to send JSON data from the client to an API endpoint named /api on my a2 web server, I encountered an issue where the connection was being refused and no logs were appearing in the terminal accessed through SSH. The ...

The error message states: "An attempt was made to destructure a non-iterable object. In order for non-array objects to be iterable, they must have a [Symbol.iterator

I need to call a RTK query endpoint from a function const [getCityCode, { isLoading, error, data, isSuccess, isError }] = useLocationQuery(); const getLocationDetails = async () => { const queryItems = { latitude: lat, longitude: long }; await getC ...