ZeDonDino
ZeDonDino

Reputation: 5352

How to check over what element my mouse is when I lose focus on input element

Let's say I have this:

<body>
<input type="text" onblur="myFunction()" />

<... rest of page ...>

</body>


<script type="text/javascript">

    function myFunction()
    {
        //this function alerts over what element your mouse is when the input loses focus
    }
</script>

Does someone know how to implement this?

Upvotes: 0

Views: 1590

Answers (1)

Cerbrus
Cerbrus

Reputation: 72937

You could track what element your mouse if hovering over, like this:

<input type="text" id="myInput" onblur="myFunction()" />
var input = document.getElementById('myInput'), // Get the input element
    focus;

input.onmouseover = input.onfocus = function(){focus = true;}; // Set focus to true if the input gains focus
input.onmouseout = input.onblur = function(){focus = false}; // Set focus to false if the input loses focus

document.body.onmousemove = function(e){
    if(!focus){ // Only log the target is the input doesn't have focus
        console.log(e.target); //Log the current element the mouse is hovering over.
    }
};

As far as I know, there's no accurate way to check the mouse's current target on the "mouseleave" or "blur" events, since the event.target of those functions will point to the element the mouse just left, not to the element the mouse is currently hovering over.

Edit:
I added some code so it only logs when the input doesn't have focus.

Upvotes: 5

Related Questions