0

How do I get a pretty simple true/false-statement if the mouse is over a div event = true else event = false

  var test = $("#main-nav").on("mouseenter", function (e) {
    e.preventDefault();
    console.log(e.preventDefault());
    return true;
});

if (test === true) {
   //do something
} else {
   //something different
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
craphunter
  • 961
  • 2
  • 13
  • 34
  • 1
    Do you want this constantly updating as the user moves the mouse around, or do you need to know once "Is the mouse currently over element `#main-nav`". – Jamiec Nov 25 '14 at 16:45
  • http://api.jquery.com/on/ use it like $(document).on('mouseenter', '#main-nav', function(){...}); – Sen Jacob Nov 25 '14 at 16:48
  • Answer for vanilla JS https://stackoverflow.com/a/46972433/1205871 – danday74 Aug 02 '22 at 01:41

3 Answers3

6

If I understand your question correctly:

if($("#main-nav").is(":hover")) {
   //do something
}else{
   //something different
}

In pseudo code:

if the cursor is over #main-nav
    do something
if it's not
    do something else

If you want test to always be set:

var test = false;
$("#main-nav").on("mouseenter", function(e){
    e.preventDefault();
    test = true;
}).on("mouseleave", function(e){
    e.preventDefault();
    test = false;
});

This way,

if(test === true) {
   //do something
}else{
   //something different
}

will always work.

Mooseman
  • 18,763
  • 14
  • 70
  • 93
0

You can have a boolean (true/false) variable that will constantly update by doing this:

var hovering;
$("#main-nav").mouseenter(function(){
    hovering = true;
});
$("#main-nav").mouseleave(function(){
    hovering = false;
});

So whenever it is called it will tell you if the mouse is within your div:

if (hovering){
    // mouse within div
} else {
    // mouse not within div
}
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
0

If you necessarily need is as a variable:

var test = false;
$("#main-nav").on("mouseenter", function (e) {
    test = true;
});
$("#main-nav").on("mouseout", function (e) {
    test = false;
}); 

//....

if (test === true) {
   //do something
} else {
   //something different
}
pbogut
  • 857
  • 1
  • 9
  • 22