javascriptjquerymousemove

Limit mousemove event


how can i limit the mousemove event to a certain area, let's say a div in the middle of the page? Thanks in advance

if (window.screen.width > 765)
if (matchMedia('(pointer:fine)').matches) 
$(document).ready(function() {
  $(this).on("mousemove", function(e) {
    var x = e.pageX;
    var y = e.pageY;
    var el = $(".title");
    el.css('position', 'absolute');
    el.css("left", x);
    el.css("top", y);
  })
})

Solution

  • So, you just need to attach the mouseevent to the target element, you need the mouseevent limit to

    $('#specificDiv').on("mousemove", function(e) {
      var offset = $(this).offset();
    
      var x = e.pageX - offset.left;
      var y = e.pageY - offset.top;
    
      var el = $(".title");
      el.css('position', 'absolute');
      el.css("left", x);
      el.css("top", y);
    });
    body {
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    #specificDiv {
      width: 200px;
      height: 200px;
      background-color: #f5f5f5;
      position: absolute;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="specificDiv">
      <div class="title">title</div>
    </div>