steel
steel

Reputation: 12520

Click through element but detect hover

I have an element that sits in the middle of my page as a sensor. That element is larger than the area underneath it, which contains links. I need to be able to both register when the mouse is over / moves over the sensor, as well as click the links below.

I've looked on SO, but I can't find a solution that works for my issue given that I need this circular sensor to float in the middle of the page.

#css
.sensor {
  pointer-events: none; # does not register jquery's mouseenter, but allows the links to be clicked
}

#javascript
$('.sensor').mouseenter(doStuff) #only works if pointer events are enabled

Here's a fiddle of a basic mockup:

http://jsfiddle.net/3rym41ra/

Thanks in advance.

Upvotes: 1

Views: 778

Answers (1)

Fuzzyma
Fuzzyma

Reputation: 8474

I placed a circular sensor on the page which changes the background when hovered. Since the sensor now is a parent of the links, all events will bubble up. You can click on the elements while still using certain areas of the sensor as you like

$('body').mousemove(function(e) {

  // We want it circular on page so we take 50% left and 50% top as the middle
  // Cirle has radius = 100px

  var middle = {
    x: $(window).width() / 2,
    y: $(window).height() / 2
  }; // Our middle-point
  var normalize = {
    x: middle.x - e.pageX,
    y: middle.y - e.pageY
  }; // mouse-position relative to the middle
  var radius = 100; // radius

  // some Math
  if (normalize.x * normalize.x + normalize.y * normalize.y < radius * radius) {
    // inside circle
    $('body').css('background', 'red');
  } else {
    // outside
    $('body').css('background', 'white');
  }


})
body,
html {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#">One</a>
<a href="#">Two</a>
<a href="#">Three</a>
<a href="#">Four</a>

Upvotes: 1

Related Questions