Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accurately detect mouseover event for a div with rounded corners

I am trying to detect a mouseover event on a circle. I define the circle div like this:

.circle {
  width: 80px;
  height: 80px;
  -moz-border-radius: 40px;
  -webkit-border-radius: 40px;
  background-color: #33f;
}

Then I detect the mousover using jQuery like this:

$('.circle').mouseover(function() {
  $(this).css({backgroundColor:'#f33'});
});

This works well, except that the entire 80px by 80px area triggers the mouseover event. In other words, just touching the bottom right corner of the div triggers the mouseover event, even though the mouse is not over the visible circle.

Is there a simple and jquery friendly way to trigger the mouseover event in the circular area only?

Update: For the sake of this question, let's assume that the browser is CSS3 capable and renders the border-radius correctly. Does anyone have the mad math/geometry skills to come up with a simple equation to detect whether the mouse has entered the circle? To make it even simpler, let's assume that it is a circle and not an arbitrary border radius.

like image 955
Devon Avatar asked Jan 05 '10 13:01

Devon


3 Answers

Just ignore the mouseover event if the mouse's position is too far away. It's really simple. Take the center point of the div, and calculate the distance to the mouse pointer (distance formula = sqrt((x2 - x1)^2 + (y2 - y1)^2)) and if it's larger than the radius of the circle (half the width of the div), it's not in the circle yet.

like image 55
Malfist Avatar answered Nov 19 '22 14:11

Malfist


No, there is not. Think in geometrical terms. You're still using a div, which is a box element. That box element has a specific rectangular boundary that triggers the mouse over event. The use of CSS to supply a rounded border is cosmetic only, and does not change the rectangular boundary of that element.

like image 4
Chris Avatar answered Nov 19 '22 15:11

Chris


You can probably do something like that with an old-fashioned image map - there's a circular area.
In fact, this plugin can help you: jQuery MapHilight Plugin

like image 2
Kobi Avatar answered Nov 19 '22 15:11

Kobi