Search code examples
javascriptmouseeventmouse-cursor

How do you get computed cursor type in javascript?


I want to change an element when the cursor changes its type, for instance when the cursor changes from pointer to a text (I-beam).

I have tried to use

document.addEventListener('mouseover', e => {
  const tgt = e.target;
  const computed = window.getComputedStyle(tgt)["cursor"]
  console.log("Computed: " + computed)
});

but this just logs "Computed: auto". I want the know the cursor type specifically. I don't know if this is possible?


Solution

  • first, you need to define cursor style for one of your elements like this:

    <style>
    
    #cur{
        cursor: pointer;
    }
    
    </style>
    

    and then when mouseover on your element, it will change from auto to pionter

     <div id="cur">mouse over</div>
    
    <script>
    
    
    document.addEventListener('mouseover', e => {
      const tgt = e.target;
      const computed = window.getComputedStyle(tgt)["cursor"]
      
      
        if(computed !== "auto"){
            console.log(computed);
        }
    
    });
    
    
    </script>