Can a JavaScript function be used with images to operate across multiple elements?

How can I make a function work on multiple elements?

let image = document.getElementById("opacityLink");

image.onmouseover = function() {
  image.style = "opacity:0.9";
};

image.onmouseout = function() {
  image.style = "opacity:1";
};
<div class="news col-xxl-4 col-xl-4">
  <a href="/index.html" id="opacityLink" name="opacityLink">
    <div class="img-news">
      <img src="img_nature.jpg" alt="Image">
    </div>
    <div class="info-news">
      <div class="date">
        2023.07.02
      </div>
      <div class="title-news">
        <h2>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis, soluta.</h2>
      </div>
      <div class="excerpt-news">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit sed perspiciatis nihil voluptas qui quaerat tempore quibusdam inventore reiciendis, minima tempora quasi.</p>
      </div>
    </div>
  </a>
</div>

I have tried using getElementsByClassName and getElementById but it's not working. When using ID, only one link works, but I have 9 similar links and I want the JavaScript code to apply to all 9.

Answer №1

To ensure each link has a unique styling, assign a specific class to each link element. For instance: class="hover-opacity"

Subsequently, utilize querySelectorAll to select all elements with the specified class and iterate through them:

document.querySelectorAll('.hover-opacity').forEach(link => {
     link.onmouseover = function() {
          link.style = "opacity:0.9";
     };
     link.onmouseout = function() {
          link.style = "opacity:1";
     };
});

However, it is recommended to achieve this effect using purely CSS:

.hover-opacity:hover {
      opacity: 0.9;
}

Answer №2

Maybe we could simply add a class and use CSS only to achieve this effect?

.linky-thing:hover {
  opacity: 0.9;
}
<link href="
https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c2cfcfd4d3d4d2c1d0e0958e938e90">[email protected]</a>/dist/css/bootstrap.min.css
" rel="stylesheet">
<script src="
https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="781a17170c0b0c0a1908384d564b5648">[email protected]</a>/dist/js/bootstrap.min.js
"></script>

<div class="news col-xxl-4 col-xl-4">
  <a class="linky-thing" href="/index.html" id="opacityLink" name="opacityLink">
    <div class="img-news">
      <img src="img_nature.jpg" alt="Nuotrauka">
    </div>
    <div class="info-news">
      <div class="date">
        2023.07.02
      </div>
      <div class="title-news">
        <h2>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis, soluta.</h2>
      </div>
      <div class="excerpt-news">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit sed perspiciatis nihil voluptas qui quaerat tempore quibusdam inventore reiciendis, minima tempora quasi.</p>
      </div>
    </div>
  </a>
  <div class="news col-xxl-4 col-xl-4">
    <a class="linky-thing" href="/index.html" id="opacityLink2" name="opacityLink2">
      <div class="img-news">
        <img src="img_nature.jpg" alt="Nuotrauka">
      </div>
      <div class="info-news">
        <div class="date">
          2023.07.02
        </div>
        <div class="title-news">
          <h2>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis, soluta.</h2>
        </div>
        <div class="excerpt-news">
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit sed perspiciatis nihil voluptas qui quaerat tempore quibusdam inventore reiciendis, minima tempora quasi.</p>
        </div>
      </div>
    </a>
  </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

Is it feasible to pre-load external websites using JavaScript?

While searching on various platforms, including Stack Overflow, I couldn't find a solution to this specific query. I'm not necessarily seeking an implementation already in place, but rather ... Imagine having an intranet application that loads q ...

What is the method for integrating an element into a different flow using the position property?

How can I solve the following issue: I am working with a carousel markup that has the same HTML structure as shown below. <div> // Contains the carousel slide <div> <ul> <li><img src={....} /></li> <li ...

Comparing the Length of JavaScript Arrays

I have code that checks for similar values in two arrays, and if there are any, they are not displayed in the result. However, when I switch the lengths of the arrays so that Array2 is longer than Array1, I end up with an empty result array. How can I achi ...

Is there a way to fetch API data selectively rather than all at once?

Hello everyone, I successfully managed to retrieve data from the Star Wars API in JSON format and display it on my application. Initially, I set the state as 'people.name' to obtain the name object. However, this also rendered unwanted data when ...

The issue with React Testing using Jest: The domain option is necessary

I've recently developed a React app that implements Auth0 for Authentication. Right now, I'm working on setting up a test suite using Jest to test a specific function within a component. The function I want to test is createProject() in a React ...

There appears to be an issue with Mongoose Unique not functioning properly, as it is allowing

Below is the complete code snippet I am using to validate user data: import { Schema, model } from 'mongoose'; import { User } from './user.interface'; const userSchema = new Schema<User>({ id: { type: Number, required: ...

Is there a way to launch Visual Studio Code using a web browser?

Is there a way to launch "Visual Studio Code" automatically upon clicking a button on my website? ...

IE9 causing issues with Angularjs ng-route - views fail to display

I am new to AngularJS and currently working on developing an application using AngularJS along with Coldfusion for database data retrieval. However, I am facing compatibility issues specifically with IE9 (which is the default browser in my office). The ap ...

How to utilize a specific option as a variable within a PHP select dropdown menu

In my PHP code, I am retrieving data from an Azure SQL database and using it to populate a drop-down menu with options. The SQL query I used returns two columns: Title and Cycle_ID. After setting the Title as the text string and Cycle_ID as the value for ...

The Bootstrap modal-backdrop dilemma requiring JavaScript intervention

I am encountering some problems with the Bootstrap modal. When I try to open a modal, everything looks good, but when I close it, the screen turns completely black. Upon closer inspection, I found that every time I click on the X to close the modal, there ...

Comparing attribute selectors to class selectors in the realm of styling

I often come across code that looks like this: <input type="text" class="class1" name="text"> <input type="submit" class="class2" name="submit"> which is then styled as follows: input[type=text] { styles here...} input[type=submit] { sty ...

Animating a mesh in three.js with color transitioning using tween.js

I've been struggling to accomplish this task. My goal is to change the color of a ConvexGeometry mesh when hovered over. So far, I can successfully change the mesh's color without any issues. The problem arises when I attempt to create a smooth ...

ID is not receiving the CSS styles

I'm having trouble applying my CSS to a specific img ID element on the page. I've been trying to solve this for about 30 minutes with no luck. The strange thing is, I have two other elements with the same HTML and CSS that are working correctly. ...

How can I take a screenshot from the client side and save it on the server side using PHP?

Currently, I am exploring the possibility of screen capturing at the client side. It appears that the "imagegrabscreen()" function can only capture screens on the server side. After some research, I discovered a new function that allows for screen capture ...

Repositioning the final row to the bottom of the container in Bootstrap 4

I am working on a simple footer design that includes contact information in three rows. The first two rows should appear at the top, while the last row needs to be positioned at the very bottom of the container. To achieve this layout, I decided to use abs ...

What is the best way to run a lengthy task in Node.js by periodically checking the database for updates?

In my current setup, there is a routine that continuously checks the database for any pending work orders. Upon finding one, it needs to execute it promptly. The system can handle only one work order at a time, and these tasks may vary in duration from 5 s ...

The ng-view DIV in Angular JS 1.x mysteriously vanishes

Currently, I am working on a project that involves angularJS and ASP.NET in Visual Studio 2013. However, I have encountered a frustrating issue where my DIV node for ng-view is being replaced with an ng-view comment without any errors appearing while testi ...

Delete the designated column from the table

I am having difficulty with hiding and showing table columns using checkboxes. I need to eliminate the Mars column (in bold) along with its corresponding data (also in bold). Once the Mars column is removed, I want the Venus column and its data values to ...

Is there a way to prevent pixels from being rendered outside of a designated rectangle in HTML5?

I'm looking to add screen-in-screen functionality to my HTML5 game, and I have an idea for how to approach it: //Function called every frame function draw(){ set a mask rectangle only draw pixels from the current frame that fall within this recta ...

Tips for preventing the extraction of resolve from promises and initiating a process before a callback

There is a common pattern I frequently find myself using: const foo = () => { const _resolve; const promise = new Promise(resolve => _resolve = resolve); myAsyncCall(_resolve); return (dataWeDontHaveYet) => promise.then(cb => c ...