How can I track if the cursor is over a certain element?

3 answers 3

You need to connect a listener to the mouseover event element, for example, if with jquery:

 $("element_selector").on("mouseover", function(e){ // любой код }) 

if pure js:

 document.getElementById('elementId').onmousemove = function(e){ // любой код } 

You can read about mouse events here. Here (in Russian)

  • There was no mention of jQuery in the question. - Grundy
  • If without jquery, you can do this: document.getelementById('elementId').onmousemove = function(e){ // любой код} - Mikl
  • one
    Take out this code in response. PS he is not working. - user207618
  • made a worker, thanks!) - Mikl
  • @Mikl, why in the example with jQuery mouseover , and without - mousemove ? - Grundy

Option if already subscribed to mousemove -

 document.addEventListener('mousemove', document_mouseMoveHandler); function document_mouseMoveHandler(event) { let element = document.elementFromPoint(event.clientX, event.clientY); let isSecondValid = isSecond(element.dataset.id); let info = document.querySelector('.validator-output') info.textContent = isSecondValid; } function isSecond(value) { return value === "second" } 
 main { padding: 15px } .container { width: 100%; height: 100%; display: flex; justify-content: space-around; position: relative; } .child { width: 100px; height: 100px; background: tomato; text-align: center; display: flex; } .informer { width: 100%; height: 30px; position: relative; padding: 15px; display: flex; justify-content: space-around; } .child > span { color: white; margin: auto; pointer-events: none; } 
 <main> <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" /> <body> <div class="container"> <div class="child" data-id="first"><span>first</span> </div> <div class="child" data-id="second"><span>second</span> </div> <div class="child" data-id="third"><span>third</span> </div> </div> <div class="informer"> <span>is second: <span class="validator-output">false</span></span> </div> </main> 

  • and if not signed? - Grundy

 var text = document.getElementById('text'); text.onmouseover = function(){ this.style.color = 'red'; //курсор над элементом } text.onmouseleave = function(){ this.style.color = '#000';//курсор покинул элемент } 
 p{ font-size: 40px; } 
 <p id="text" >Some text</p> 

  • Please try to write more detailed answers. I am sure the author of the question would be grateful for your expert commentary on the code above. - Nicolas Chabanovsky