Home > database >  I target all links using a.forEach((item) ...is it possible to include 'or class x' when n
I target all links using a.forEach((item) ...is it possible to include 'or class x' when n

Time:08-21

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);
 });
});

CodePudding user response:

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) => {
   ...
});
  • Related