There is a library called jQuery Outside Events that implements "outside" events that are executed when event occurs outside the element in question.
These are the events "from outside": clickoutside, dblclickoutside, focusoutside, bluroutside, mousemoveoutside, mousedownoutside, mouseupoutside, mouseoveroutside, mouseoutoutside, keydownoutside, keypressoutside, keyupoutside, changeoutside, selectoutside, submitoutside
Below an example of the event mouseoveroutside that is fired when mouse is outside the element.
/*
* jQuery outside events - v1.1 - 3/16/2010
* http://benalman.com/projects/jquery-outside-events-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(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){l.target=k;j.apply(this,arguments)}}};function f(i){$(d).each(function(){var j=$(this);if(this!==i.target&&!j.has(i.target).length){j.triggerHandler(e,[i.target])}})}}})(jQuery,document,"outside");
$(function(){
var elem = $("#elemento");
// quando o mouse estiver sobre o elemento
elem.bind('mouseover', function(event){
console.log()
$(this)
.removeClass('dentro')
.children('#header').text('Dentro');
});
// evento quando o foco do mouse estiver fora do elemento
elem.bind('mouseoveroutside', function(event){
$(this)
.addClass('dentro')
.children('#header').text('Fora');
});
});
#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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="elemento">
<h1 id="header"></h1>
</div>
Github of the Project
I’m a beginner in js, how can I make sure that if this is true, run a line of code? Thank you!
– Leonardo
@Leonardocarmo
if(mouseFora) { ... }
or simply (if not to reuse the variable)if ( !$(meuElemento).is(":hover") ) { ... }
(in other words, what I am saving in the variablemouseFora
is a Boolean, which can be used directly in a comparison)– mgibsonbr
That’s right, buddy! Thank you very much!
– Leonardo
@Leonardocarmo Sure he wants to mark my answer as accepted? That of the Kaduamaral is much more complete... :)
– mgibsonbr
I liked his, however for what I needed the setTimeout is not necessary, because the page already updates alone, so it is not necessary. I just really needed this!
– Leonardo