1

I have a group of about 40 pictures on a website page of past scholarship recipients. I would like to add the picSize and picReturn functions to each picture as mouse event function or event listener without writing separate variables using getElementById...I would rather iterate through the array of pics using getElementsByClassName and assign the event to every pic.

Is there a way to apply an event listener to an entire class of elements?

let studentPic = document.getElementById("recipient-image1");


const picSize = () => {

  studentPic.style.height = "342px";
  studentPic.style.width = "300px";
  studentPic.style.left = '20%';
  studentPic.style.zIndex = '1';
}
const picReturn = () => {
  studentPic.style.height = "";
  studentPic.style.width = "";
  studentPic.style.left = '';
 studentPic.style.zIndex = '';
}

studentPic.addEventListener('mouseover', picSize);

studentPic.onmouseout = () => {
   picReturn()
}
KSTREET88
  • 11
  • 1
  • `Is there a way to apply` ... `iterate through the array of pics using getElementsByClassName`...you've answered your own question – ADyson Mar 12 '21 at 15:49
  • 1
    With these changes there's no need for JavaScript at all... Add a class (e.g. `recipient-image`) and then define the changes with the pseudo selector `:hover` and you're done -> `.recipient-image :hover { ... }` – Andreas Mar 12 '21 at 15:52
  • So if you rather would use `getElementsByClassName` why don't you do just do it? – derpirscher Mar 12 '21 at 15:52

1 Answers1

0

Yes.

var elements = document.getElementsByClassName("classname");

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('mouseover', picSize);
}
Chris Strickland
  • 3,388
  • 1
  • 16
  • 18
  • Thanks for the answer....My next question would be how would I alter the contents of the picSize function. using the variable studentPic isnt working. – KSTREET88 Mar 12 '21 at 16:42
  • If I understand what you want to do, I think you would replace `studentPic` with `this`, but I think you might be just as well off to take Andreas' suggestion of using css to accomplish this. – Chris Strickland Mar 12 '21 at 16:48