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

I target all links using a.forEach((item) …is it possible to include 'or class x' when needing to target non-anchors?

This script is on a custom Javascript cursor. It works as intended, however I want the mouse to react the same way when it hovers over an single element (img) that is not an a – which is what the script currently targets.

Is there a way I can adapt the script to essentially look for ‘target anchors or an element with a class of .link’ (for example). Or would I need to duplicate the block of code and use getElementsByClassName? Maybe I’d be better off using something like my data- to target elements rather than all a elements?

document.addEventListener("mousedown", function () {
  cursor.classList.add("cursor--click");
});

document.addEventListener("mouseup", function () {
  cursor.classList.remove("cursor--click");
});

a.forEach((item) => {
 item.addEventListener("mouseover", () => {
    cursorTrail.classList.add("cursor-trail--hover");
 });
 item.addEventListener("mouseleave", () => {
   cursorTrail.classList.remove("cursor-trail--hover");
 });
});

a.forEach((item) => {
 const interaction = item.dataset.interaction;

 item.addEventListener("mouseover", () => {
   cursor.classList.add(interaction);
 });
 item.addEventListener("mouseleave", () => {
   cursor.classList.remove(interaction);
 });
});

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 :

You can select elements using an arbitrary CSS-selector by using document.querySelectorAll

In your case, you would do something like this:

let links = document.querySelectorAll('a, .link');
links.forEach((item) => {
   ...
});
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