jQuery Mouse Event Position Relative to an Element

Introduction

Use the jQuery event.pageX and event.pageY

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Find Coordinates of Mouse Pointer Relative to an Element</title>
<style>
    #box{/*from  ww w  .  ja  v a  2  s.co m*/
        width:400px;
        height:300px;
        background: #f2f2f2;
        border: 1px solid #000;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function() {
        $("#box").mousemove(function(event){
            var relX = event.pageX - $(this).offset().left;
            var relY = event.pageY - $(this).offset().top;
            var relBoxCoords = "(" + relX + "," + relY + ")";
            $(".mouse-cords").text(relBoxCoords);
        });
    });
</script>
</head>
<body>
    <div id="box"></div>
    <p>Coordinates mouse pointer with respect to the DIV box: 
    <strong class="mouse-cords"></strong></p>
</body>
</html>



PreviousNext

Related