Is it possible to choose several classes with identical names and then trigger a shared function simultaneously?

Is there a way to make this function target all elements with the class ".stop" and stop the video when any of these elements are clicked?

window.addEventListener("load", function(event) {
    window.addEventListener('scroll', checkScroll, false);
    window.addEventListener('resize', checkScroll, false);

    let playvideo = document.querySelector('video');

    let close = document.querySelector('.stop');


    close.onclick = () => {
        playvideo.pause();
    }
});

Answer №1

Representative

const main = document.getElementById('mainVideo'); // or any chosen element
main.addEventListener('click',e => {
  const targetElement = e.target;
  if (targetElement.classList.contains('halt')) {
    targetElement.closest('div').querySelector('video').pause(); // assuming the halt button is in the same div as video
  }
})

Answer №2

Big thanks to all of you for the assistance, I implemented this code and it functions just as I had hoped

    const videoElement = document.querySelector('video');

    document.querySelectorAll('.stop').forEach(stopButton => {
        stopButton.addEventListener('click', event => {
            //handle click
            videoElement.pause();
        })
    })

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

Singleton constructor running repeatedly in NextJS 13 middleware

I'm encountering an issue with a simple singleton called Paths: export default class Paths { private static _instance: Paths; private constructor() { console.log('paths constructor'); } public static get Instance() { consol ...

What is causing the issue with using classes in Javascript to clear the form?

<!DOCTYPE html> <html> <head> <title>Onreset</title> </head> <body> <form> Username: <input type="text" class="abc"><br><br> Password: <input type ...

Error: The script is unable to access the property "div" because it is undefined

I keep encountering this issue "Cannot read property 'div' of undefined" This is the snippet in question function validateData(){ for(let j = 0; j < 13; j++){ if(dataArr[j].data.textContent === resultSet[j].result.div. ...

What is the reason behind the default disabling of bootstrap multiselect options?

Just diving into the world of bootstrap and I'm puzzled as to why my simple multiselect options aren't responding when clicked. UPDATE The first multiselect option on the test-site linked below is the one giving me trouble. I've tried it o ...

Delete the event handler if the original selector used to set up the handler is unknown

I need to remove an event handler from the element. The current handler is added by a third-party plugin, and I want to prevent its behavior. As far as I know, the functions off() and unbind() require the original selector to be used. The issue arises b ...

Positioning the infowindow in Google Maps API v3

Creating a map with various markers, each with its own info window. However, when attempting to display an info window on multiple markers, the position remains fixed at the first clicked marker. What could be causing this issue? <script type="text/jav ...

When an object is pushed into an array, it gets duplicated and also appears in a proxy when viewed in the console

Working with Firebase 9 and Vue 3 in building a chat application. The issue at hand is that when I push message objects to the messages array [], the console shows duplicates like this: Proxy {0: {…}, 1: {…}} [[Handler]]: Object [[Target]]: Array( ...

Can you guide me on utilizing filter in an Apps Script array to retrieve solely the row containing a particular user ID within the cell?

I am using an Apps Script that retrieves data from four different columns in a spreadsheet. However, it currently fetches all the rows instead of just the row that matches the randomly generated 8-digit user ID. function doGet(req) { var doc = Spreadshe ...

Can you provide some insight into why the init() method is throwing an error?

My project utilizes DynamoDB access through https://www.npmjs.com/package/react-native-dynamodb. I followed the code provided on the website for implementation. The issue I'm facing is that when hovering over my .init() method in WebStorm IDE, it sho ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

Navigating to a new URL using window.location.href will seamlessly embed the new page within

I am new to JavaScript and I am facing an issue with my AJAX function. The function is supposed to navigate to a new URL, but instead of loading the new page separately as if the user had typed the URL, it gets inserted inside the same div where the button ...

What is the best way to maintain the previous input value on page refresh in Vuejs?

In my development project, I am utilizing the Laravel and Vue.js technologies. I am facing an issue where I need to set the input value to its previous old value when either refreshing the page or navigating back to it in a Vue dynamic component. Here is ...

Using HTML and JavaScript, we can set two different color values - one for the background and one for the h1 title

I am trying to save two values, one for the h1 tag and one for the body background. I want the user to select color 1 and color 2. When I press the third button, all changes should be applied and the colors should change. I have attempted this but with no ...

Has anybody managed to successfully implement this require or debug NPM module for use in a web browser?

Has anyone successfully implemented the require or debug NPM modules in a browser environment? Despite claims and instructions on the debug NPM module's page that it can be used in the browser, attempting to do so results in the following error: Unc ...

Unable to retrieve the value of a specific property using _.map based on its property name

I'm currently facing a challenge with my app that utilizes MongoDB as its database. Specifically, I am having trouble extracting property values from array variables. Despite using a _.forEach method to confirm the presence of data, I encountered diff ...

Utilizing Google's Recaptcha v2 to enhance website security and effectively prevent

My website incorporates an ajax form with Google reCAPTCHA. I have utilized event.preventDefault() to prevent the page from refreshing. Prior to integrating the captcha, everything functioned correctly. However, now whenever I attempt to submit the form, I ...

Tips for gathering all links from a JSON object

When dealing with a JSON object of any structure, simple or complex, what would be the most efficient way to extract all URLs from the data and store them in an array for iteration in JavaScript? { "url": "https://example.com:443/-/m ...

Utilizing Ajax and jQuery to verify the initial password input in real-time as the user types

My goal is to create a Change Password page where users can enter their original password and have it instantly checked for correctness without the need for page refresh. I want to display a checkbox image next to the text box when the password is correct. ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

Introduce regex in the middle

If I have a string in JavaScript like so: "test test hello test test" I understand how to replace 'hello' with 'byebye': replace("hello","byebye"); However, what is the most efficient method to add 'byebye' immediately afte ...