What is the best way to apply one JavaScript code to two separate HTML elements?

I am currently experiencing an issue where only the first mp4 file is working properly, while the second one does not. I am considering removing the stylesheet part as it is proving to be difficult for me to handle. I lack the skills to implement other solutions that have been suggested by others, so I am reaching out for help.

index.html:

    <div class="main-container">
        <div class="video-container">
          <video src="honda/honda adv.mp4"></video>
          <div class="hover-text active"><b>Autoturisme</b></div>
        </div>
      </div>
  
      <script src="main1.js"></script>


      <div class="main-container">
        <div class="video-container">
          <video src="honda/honda engine.mp4"></video>
          <div class="hover-text active"><b>Motoare</b></div>
        </div>
      </div>
  
      <script src="main2.js"></script>

style1.css (currently identical to style2.css):

.main-container {
  position: relative;
  width: 400px;
  top: -350px;
  left: -550px;
  margin: 40px auto;
  font-family: "Roboto", sans-serif;
  border-radius: 10px;
}

.video-container {
  position: relative;
}

.video-container video {
  width: 100%;
}

.video-container .hover-text {
  position: absolute;
  top: 50%;
  left: 50%;
    transform: translate(calc(-50% - 24px), -50%);
    background: #ff0019;
    color: #fff;
    padding: 8px 16px;
    border-radius: 8px;
    pointer-events: none;
    box-shadow: 4px 4px 50px -4px rgba(0, 0, 0, 0.8);
    opacity: 0;
    letter-spacing: 0.8px;
    transition: all 400ms ease;
  }
  
  .video-container .hover-text.active {
    opacity: 1;
    letter-spacing: 0;
    transform: translate(-50%, -50%);
  }

main1.js (same code as main2.js):

const video = document.querySelector(".video-container video");
const hoverText = document.querySelector(".video-container .hover-text");

video.addEventListener("mouseenter", () => {
  video.play();
  hoverText.classList.remove("active");
});

video.addEventListener("mouseleave", () => {
  video.pause();
  hoverText.classList.add("active");
});

Answer №1

If you want to implement a plugin function that requires a container selector, here's how you can do it.

Firstly, include the plugin code in your HTML and then proceed to activate it. Just ensure that the plugin script loads before you invoke VideoPlugin().

.video-container > video { background: black; }

.hover-text.active { color: green; }
<!-- Load plugin -->
<!-- <script src="video-plugin.js"></script> -->
<script>
/* The VideoPlugin is defined in a separate file called video-plugin.js */
const VideoPlugin = (selector = '.video-container') => {
  const addListeners = (videoContainer => {
    const video = videoContainer.querySelector("video");
    const hoverText = videoContainer.querySelector(".hover-text");

    video.addEventListener("mouseenter", () => {
      video.play();
      hoverText.classList.add("active");
    });

    video.addEventListener("mouseleave", () => {
      video.pause();
      hoverText.classList.remove("active");
    });
  });
  document.querySelectorAll(selector).forEach(addListeners);
};
</script>

<div class="main-container">
  <div class="video-container">
    <video src="honda/honda adv.mp4"></video>
    <div class="hover-text"><b>Autoturisme</b></div>
  </div>
</div>
<div class="main-container">
  <div class="video-container">
    <video src="honda/honda engine.mp4"></video>
    <div class="hover-text"><b>Motoare</b></div>
  </div>
</div>

<!-- Activate the plugin -->
<script>
  VideoPlugin(); // By default, the selector targets '.video-container'
</script>

Answer №2

It is possible to reference two distinct sets of identifiers in ".js" scripts. However, there could be a more efficient and sophisticated approach for managing this particular situation.

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

What is the preferred method for storing JSON data - using a single data attribute or multiple separate data attributes?

When it comes to storing multiple data attributes for a single DOM element, the question arises: Is it better to have a single data attribute containing JSON data, or is it more efficient to have separate data attributes for each value needed? <select ...

A simple method to obtain the ID of the element that has been clicked and save it in a variable to be utilized in a function responsible for

Seeking assistance in optimizing the code below by removing the specific #static id and allowing for dynamic IDs such as #dynamic within the one click function. This would eliminate the need to repeatedly copy and paste the same function with different ID ...

Tips for dynamically modifying style mode in Vue.js

I am looking to implement a feature where the style can be changed upon clicking a button. In my scenario, I am using Sass/SCSS for styling. For example, I have three different styles: default.scss, dark.scss, and system.scss. The code for dark.scss look ...

Utilizing a third-party API within the next/api endpoint

I've recently started working with NEXTJS and developed a weather application. I'm integrating the openweather API, but I'm unsure how to use it within the next/api. I attempted creating a file named today.js inside the next/api directory an ...

Show 1 Blog Post on a Separate AngularJS Page

I would like to show only Test Post 1 on the next HTML page titleDetails.html when the user clicks on Test Post 1 in index.html 1) titleDetails() in index.html: <a ng-click="titleDetails(post)">{{ post.title }} </a> 2) Controller Variables a ...

The inability to read property 0 of undefined persists despite implementing conditional rendering

I'm struggling to understand what mistake I'm making in the current situation: There's an array named arrayOfChildren that gets initialized like this: const [arrayOfChildren, setArrayOfChildren] = React.useState([]) With a handler function ...

Is there a way to include individual Facebook comments for each image within a jQuery lightbox?

After completing my own version of a lightbox using HTML5, CSS, and jQuery, I encountered an issue with the comments feature. While each image in the gallery should have separate comments, Facebook's comment system only records comments for the entire ...

Retrieve dashboard configurations in AngularJS by making an $http request prior to initiating the dashboard controller

I am currently immersing myself in Angular and tackling a complex dashboard framework all built with Angular. Prior to loading the controllers, I need to fetch various dashboard settings from the server using $HTTP. These settings play a crucial role in de ...

PHP-based LESS compiler

Is there a way to compile LESS from PHP without using node.js or ruby? I came across a PHP implementation called LESSPHP on Google, but it seems outdated and doesn't support newer features. Would using the V8js API to run less.js work, even though i ...

"Encountering an issue where the route function in Passport and ExpressJS is not being

When using passport for admin authentication, I am facing an issue where the redirect is not calling my function. Consequently, all that gets printed on login is [object Object] Here is my code: app.get('/admin', isLoggedIn, Routes.admin); ...

Having some trouble finding the input box element with Python/Selenium

I'm struggling to automate a task using Python. For some reason, I can't find the email input element with driver.find_element_by_. No matter what I try, I just can't seem to locate it. All I want is for Python to log in using Chromedriver. ...

Unveiling the enigma of unresponsive Bootstrap dropdowns

I'm working on creating a custom navigation bar using Bootstrap v5. I found the code on the Bootstrap website and copied it into my project. However, I also added some JavaScript code to enhance its functionality, but unfortunately, it's not work ...

AngularJS: default radio button selection

I'm currently working on creating a color configurator using AngularJS with radio buttons. Everything seems to be functioning properly - the data binds correctly, etc., but I'm encountering an issue setting the default color radio button as check ...

What occurs to the node request stream before it is utilized?

Currently, I am developing a node application that involves piping the body of a post request into a writable stream for saving data to disk. While working on this project, it has come to my attention that I lack knowledge about what happens to the request ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

Trouble with the ejs <%- body %> rendering properly

I plan to utilize a predefined layout template named layout.ejs, and here is the code present in the file: <html> <head> <title></title> </head> <body> <%- body %> </body> </html> Currently, I ...

Displaying information from a database in an HTML form using PHP

Seeking assistance with managing data and populating: I'm in the process of creating an Employee database with two pages: 1. Add Employee 2. Modify Employee The "Add Employee" page requires input fields for EMP Name, EMP ID, Manager name (from a dro ...

The module '@react-navigation/native' is missing or does not have its corresponding type declarations

I'm encountering an issue with my react-native app using expo and typescript. After installing the necessary libraries via npm, I can confirm they are available in the node_modules folder (see image below). https://i.sstatic.net/6riSc.png The same pr ...

Using JavaScript to create CSS animations triggered on hover

Looking for a CSS Animation that will play forward once when the mouse enters a specific div, and then play in reverse when the mouse leaves. Check out my JsFiddle here. The div with the class ".item" should trigger the mouse enter event. The animation co ...

Combine several pages from PDF files into a single document

I am currently working on developing a small electron application that combines multiple PDF files or pages into one larger page to help save paper when printing several CAD drawings. Essentially, I am looking for a cross-platform solution similar to the ...