Reputation: 3547
I have drawn a rectangle using svg in html. I need to detect the cursor position on the screen with respect to this rectangle and change its style. I need to do something like this:
if (cursor is left to the rectangle) {
background of rectangle = red;
}
else if (cursor is right to the rectangle) {
background of rectangle = blue;
}
how to determine the position of the cursor wrt the rectangle?
Upvotes: 0
Views: 1430
Reputation: 11859
you can try this:
$(document).ready(function(){
(function() {
window.onmousemove = handleMouseMove;
function handleMouseMove(event) {
event = event || window.event;
var rect = $("#rect");
var left = rect.position().left;
var width = rect.width();
var Xpos=event.clientX;
if (Xpos<left)
rect.css({"background":"red"});
else
if (Xpos>left+width)
rect.css({"background":"blue"});
}
})();
});
HTML:
<table>
<tr>
<td>Left</td>
<td id="rect">Center</td>
<td>Right</td>
</tr>
</table>
Upvotes: 0
Reputation: 8511
You can do the thing you want with jQuery
CSS:
body {
cursor:pointer;
}
td {
border:#777 1px solid;
font-family:georgia; font-size:50px;
}
#content {
background:green;
}
HTML:
<input id="left"/> (left)<br/>
<input id="width"/> (width)<br/>
<input id="pageX"/> (pageX)<br/>
<table>
<tr>
<td>Left</td>
<td id="content">Center</td>
<td>Right</td>
</tr>
</table>
JS:
$(document).ready(function(){
$(document).mousemove(function(event){
var content = $("#content");
var left = content.offset().left;
var width = content.width();
var pageX = event.pageX;
$("#left").get(0).value = left;
$("#width").get(0).value = width;
$("#pageX").get(0).value = pageX;
if (pageX<left)
content.css({"background":"red"});
else
if (pageX>left+width)
content.css({"background":"blue"});
else
content.css({"background":"green"});
});
});
See the full HTML, CSS, JS in this jsfiddle: http://jsfiddle.net/jondinham/95te26q6/
Upvotes: 2