Open In App

How to determine which element the mouse pointer move over using JavaScript ?

Given an HTML document and the task is to get the element where mouse pointer moves over. There are two approaches to solve this problem which are discussed below:

Approach 1:



Example 1: This example implements the above approach.




<!DOCTYPE HTML> 
<html
  
<head
    <title
        How to determine which element the mouse
        pointer move over using JavaScript ?
    </title
</head
  
<body style = "text-align:center;"
      
    <h1 style = "color:green;" onmouseover = "GFG_Fun()"
        GeeksForGeeks 
    </h1
      
    <p id = "GFG_UP" onmouseover = "GFG_Fun()"
            style = "font-size: 15px; font-weight: bold;"
    </p>
      
    <button onmouseover = "GFG_Fun()"
        click here 
    </button
      
    <p id = "GFG_DOWN" style
        "font-size: 24px; font-weight: bold; color: green;"
    </p>
      
    <script
        var up = document.getElementById('GFG_UP'); 
        var down = document.getElementById('GFG_DOWN'); 
        up.innerHTML = "Hover over the document to know the element."; 
          
        function GFG_Fun() { 
            var x = event.clientX;
            var y = event.clientY;
            el = document.elementFromPoint(x, y);
            down.innerHTML = el.innerHTML;
        
    </script
</body>
  
</html>

Output:

Approach 2:



Example 2: This example using the approach discussed above.




<!DOCTYPE HTML> 
<html
  
<head
    <title
        How to determine which element the mouse
        pointer move over using JavaScript ?
    </title
</head
  
<body style = "text-align:center;"
      
    <h1 id = "h1" style = "color:green;"
            onmouseover = "alert(this.id)"
        GeeksForGeeks 
    </h1
      
    <p id = "p" onmouseover = "alert(this.id)"
            style = "font-size: 15px; font-weight: bold;"
        Hover over the document to know the element.
    </p>
      
    <button id = "button" onmouseover = "alert(this.id)"
        click here 
    </button
</body
  
</html>

Output:


Article Tags :