0

I'm modeling my flashlight effect off of this tutorial.

The problem I'm having is when the window width is larger than my actual container. When this happens, the flashlight is no longer centered on the cursor.

Take a look at this fiddle for a better understanding. Result link on Fiddle

$(document).ready(function(){
  $('.content-wrap').mousemove(function(e) {
    $('#flashlight').css({
      'left': e.clientX-960,
      'top': e.clientY-523
    });
  });
});
.content-wrap {
  max-width:960px;
  width:100%;
  min-height: 592px;
  margin:0 auto;
  position: relative;
  overflow: hidden;
  background: blue;
}

#flashlight {
  background: url(https://s3.amazonaws.com/ip-devs/AllState/keep-your-sanity/img/flashlight.png) center center no-repeat;
  position:absolute;
  z-index:999;
  height:1046px;
  width:1920px;
  pointer-events:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content-wrap">
      <div id="flashlight"></div>
    </div>
Rohit Goyani
  • 1,246
  • 11
  • 26
itsclarke
  • 8,622
  • 6
  • 33
  • 50

3 Answers3

0

The trick here is the values that set the offset.

.content-wrap {
  max-width:960px;
  width:100%;
  min-height: 592px;

and

'left': e.clientX-960,
'top': e.clientY-523

Those values should not be hard-coded.

durbnpoisn
  • 4,666
  • 2
  • 16
  • 30
0

If your flashligt is absolute relative to the document root, use e.pageX instead of e.clientX (same for Y) as detailed in this answer: onMouseMove get mouse position

Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74
0

figured out i need to get the position within the div itself and not the screen, so posting my solution here for any future trouble shooting:

$('.content-wrap').mousemove(function(e) {
  var x = e.pageX - this.offsetLeft;
  var y = e.pageY - this.offsetTop;
  $('#flashlight').css({
    'left': x-960,
    'top': y-523
  });
});

Check on JsFiddle

Rohit Goyani
  • 1,246
  • 11
  • 26
itsclarke
  • 8,622
  • 6
  • 33
  • 50