Robson
Robson

Reputation: 1277

How to check if mouse position is on the bottom area of div

I have a few sections and I want to change mouse cursor if mouse is on the area for example 200px at bottom in this section.

I tried with that code, but it works only for first section. e.pageY isn't reset in next sections.

$("section").on('mousemove', function(e){
var sectionHeight = $(this).height();
  var vertical = e.pageY;
  console.log(vertical);
  if(vertical > (sectionHeight - 200)) {      
    $('body').css("cursor","pointer");
  } else{
    $('body').css("cursor","auto");
  }
}); 

Many thanks for help.

Upvotes: 0

Views: 2989

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

Working Example.

You need to use offsetY that will give you the mouse position related to the section, check the following example :

 var vertical = e.offsetY;

Hope this helps.


$("section").on('mousemove', function(e){
  var sectionHeight = $(this).height();
  var vertical = e.offsetY;

  console.log(vertical );
  
  if(vertical > (sectionHeight - 50)) {      
    $('body').css("cursor","pointer");
  } else{
    $('body').css("cursor","auto");
  }
}); 
section{
  height:100px;
  width:100%;
  border: 2px solid #AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>AAAA</section>
<section>BBBB</section>
<section>CCCC</section>

Upvotes: 3

somethinghere
somethinghere

Reputation: 17358

Basically, there is this attribute called offsetY which tells you where the cursor is in the client's bounding box, so in this case your <section>:

$("section").on('mousemove', function(e){
  if(e.offsetY > $(this).height() - 100){      
    $(this).css("background","blue");
  } else{
    $(this).css("background","red");
  }
});
section {
  width: 100%;
  height: 400px;
  background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<section></section>

Correction

It's offsetY, not clientY.

Upvotes: 1

Related Questions