Check if the mouse is not in the element

Posted on

Question :

I want to run a code, but this code can only be executed if the mouse is not on a div . I tried the .mouseout () but it checks to see if the mouse is gone, is not it, I need to check if the mouse at that moment is not in there, if it is not running the code.

Any solution?


Answer :

Make sure the element is suffering hover , if it is not it is because the mouse is not on it:

var mouseFora = !$(meuElemento).is(":hover");



You can use % of jQuery% , as a parameter you can pass selectors, functions, elements and selection, more details in documentation .


$(document).on('click', '.executa', function(event){
   // Obs: setTimeout apenas para dar tempo de colocar ou tirar o mouse
   // da área para realizar testes. Em uma situação real
   // já se usa o IF direto
     if ($('#area').is(':hover')){
    	alert('Mouse na área');
     } else  {
    	alert('Mouse fora da área');
  }, 2000);
<script src=""></script><divid="area"></div>
<button class="executa">Executa</button>


There is a library called jQuery outside events that implements events ” from outside “that are run when event occurs outside the element in question.

Below is an example of the mouseoveroutside event that is triggered when the mouse is outside the element.

 * jQuery outside events - v1.1 - 3/16/2010
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
(function($,c,b){$.map("click dblclick mousemove mousedown mouseup mouseover mouseout change select submit keydown keypress keyup".split(" "),function(d){a(d)});a("focusin","focus"+b);a("focusout","blur"+b);$.addOutsideEvent=a;function a(g,e){e=e||g+b;var d=$(),h=g+"."+e+"-special-event";$.event.special[e]={setup:function(){d=d.add(this);if(d.length===1){$(c).bind(h,f)}},teardown:function(){d=d.not(this);if(d.length===0){$(c).unbind(h)}},add:function(i){var j=i.handler;i.handler=function(l,k){;j.apply(this,arguments)}}};function f(i){$(d).each(function(){var j=$(this);if(this!!j.has({j.triggerHandler(e,[])}})}}})(jQuery,document,"outside");

  var elem = $("#elemento");

  // quando o mouse estiver sobre o elemento
  elem.bind('mouseover', function(event){

  // evento quando o foco do mouse estiver fora do elemento
  elem.bind('mouseoveroutside', function(event){    
  #elemento {
    font-family: Arial;
    color: black;
    width: 150px; 
    height: 150px; 
    border-radius: 5px; 
    text-align: center; background-color: #CCC;
  #elemento.dentro { background-color: RoyalBlue; color: white; }
<script src=""></script><divid="elemento">
  <h1 id="header"></h1>

Project Github


Leave a Reply

Your email address will not be published. Required fields are marked *