Search code examples
javascripthtmlcsscursor-position

Detect mouse position with respect to an element


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?


Solution

  • 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/