javascripthtmlcsscustom-cursor

Custom Cursor Issues


I'm currently developing my Website and I have Implemented a Custom Cursor with CSS and JS But the problem I'm facing is that the Custom Cursor is animated and it does animate on the first link but doesn't on the others links on the website I even tried adding specific classes, Id, directly getting them by their tags but it doesn't seem to work If anyone could help that would be so nice of you.

let mouseCursor = document.querySelector(".cursor");
let mouseCursor2 = document.querySelector(".cursor2");
let hover = document.querySelector("a");

window.addEventListener("mousemove", cursor);

function cursor(e){
   mouseCursor.style.top = e.pageY + "px",
   mouseCursor.style.left = e.pageX + "px";
   mouseCursor2.style.top = e.pageY + "px",
   mouseCursor2.style.left = e.pageX + "px";
}


$(hover).hover(function() {
    hover.addEventListener("mouseleave", function(){
        mouseCursor.classList.remove("hover"),
        mouseCursor2.classList.remove("hide");
    });
    hover.addEventListener("mouseover", function(){
        mouseCursor.classList.add("hover"),
        mouseCursor2.classList.add("hide");
    });
});

Solution

  • document.querySelector only selects single node (the first node that matches the selector).

    use document.querySelectorAll if you want to select all the elements matching the selector.

    let mouseCursor = document.querySelector(".cursor");
    let mouseCursor2 = document.querySelector(".cursor2");
    let hover = document.querySelectorAll("a");
    
    window.addEventListener("mousemove", cursor);
    
    function cursor(e){
       mouseCursor.style.top = e.pageY + "px",
       mouseCursor.style.left = e.pageX + "px";
       mouseCursor2.style.top = e.pageY + "px",
       mouseCursor2.style.left = e.pageX + "px";
    }
    
    
    hover.forEach(el => {
    
        el.addEventListener("mouseleave", function(){
            mouseCursor.classList.remove("hover"),
            mouseCursor2.classList.remove("hide");
        });
    
        el.addEventListener("mouseover", function(){
            mouseCursor.classList.add("hover"),
            mouseCursor2.classList.add("hide");
        });
    })