Search code examples
javascriptjquerycsscursormouseevent

Div follow cursor only within specific parent


I would like a div .drag-indicator to follow the cursor, and disappear once a click occurs. The below code achieves this, however I only want this behaviour to happen when hovering over a specific div .carousel. The current code make .drag-indicator follow the mouse regardless of position on the screen, and when any click is made, not just within that div.

I'm sure my code could be streamlined somewhat too, so any advice here would be great. I'd like to make it just a single function.

Thanks.

/* Follow cursor */
$(document).on('mousemove', function(e) {
  $('.drag-indicator').css({
    left: e.pageX,
    top: e.pageY
  });
});

/* Hide when clicked */
$(document).on('mousedown', function(e) {
  $('.drag-indicator').fadeOut(300)
});
.drag-indicator {
  position: absolute;
  width: 50px;
  height: 50px;
  border-radius: 100%;
  background-color: red;
  z-index: 9999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel">
  <div class="carousel-cell">CELL CONTENT</div>
  <div class="carousel-cell">CELL CONTENT</div>
  <div class="carousel-cell">CELL CONTENT</div>
  <div class="drag-indicator">DRAG INDICATOR</div>
</div>


Solution

  • To make this work as you require, attach the event handlers directly to .carousel instead of the document:

    $('.carousel').on({
      mousemove: function(e) {
        $('.drag-indicator').css({
          left: e.pageX,
          top: e.pageY
        })
      },
      mousedown: function(e) {
        $('.drag-indicator').fadeOut(300)
      }
    });
    .drag-indicator {
      position: absolute;
      width: 50px;
      height: 50px;
      border-radius: 100%;
      background-color: red;
      z-index: 9999;
    }
    
    .carousel {
      border: 1px solid #C00;
    }
    
    .carousel .drag-indicator {
      display: none;
    }
    .carousel:hover .drag-indicator {
      display: block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="carousel">
      <div class="carousel-cell">CELL CONTENT</div>
      <div class="carousel-cell">CELL CONTENT</div>
      <div class="carousel-cell">CELL CONTENT</div>
      <div class="drag-indicator">DRAG INDICATOR</div>
    </div>