Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript function with image, works on multiple elements?

How to do function would work on multiple elements?

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

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

deomImage.onmouseout = function() {
  deomImage.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="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>

I tried with getElementsByClassName, with getElementById but not work. With ID works only 1 link, but I have 9 such links and I want the JavaScript code to work with all 9.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a class for each link, for example

class="opacity-link"

Then use querySelectorAll and loop through them.

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

Though it would be much better to do it with just CSS instead.

.opacity-link:hover {
      opacity: 0.9;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading