0

I am trying to detect the mouseover event on multiple elements, preferably by class.

For example:

<div class="myElement">1</div> <div class="myElement">2</div> <div class="myElement">3</div> <div class="myElement">4</div> 
selectClass("myElement").onmouseover = function() { console.log("Detected mouse!"); }​; 
6
  • What does selectClass do, and return? Commented May 19, 2020 at 17:19
  • @Taplar exactly - my example above is just so people understand what I need Commented May 19, 2020 at 17:22
  • @Nanoo if you put undefined methods in your question, we can't help you. Because we do not know what the logic does. Please provide that method definition so we can debug. Commented May 19, 2020 at 17:23
  • undefined methods? the functions aren't defined, it's just an example. Commented May 19, 2020 at 17:24
  • Why are you making up methods to put in your question? Don't do that. Just provide the information regarding what you currently have and state your problem. Making up logic that doesn't relate to anything in your code base will just confuse everyone. Commented May 19, 2020 at 17:25

3 Answers 3

1

With the code below you get all the elements with the classname "myElement" and loop over them. The loop adds an event listener so when you click on the element it calls the function elementClicked which in return logs "An element was clicked!" to the console.

var elements = document.getElementsByClassName('myElement'); function elementClicked() { console.log("An element was clicked!"); } for (let i = 0; i < elements.length; i++) { elements[i].onmouseover = function() { elementClicked(); }; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting, I will give this a go to see if it works.
0

I hope I've been helpful

var x = document.getElementsByClassName("myElement"); for (let i = 0; i < x.length; i++) { x[i].setAttribute("onmouseover", "hoho()") } function hoho() { console.log("mouse") } 

Comments

0

Here is a working version:

document.querySelectorAll(".your_class").forEach(elem => { elem.addEventListener("mouseover", () => { doSomeThing(); }) elem.addEventListener("mouseout", () => { secondThing(); }) }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.