Show a Text over an Image at Mouse Location using jQuery

← PrevNext →

I am sharing a simple jQuery example showing how to dynamically position an element or how to apply CSS properties dynamically to an element using jQuery. The code example here in this post explains how to show a text over an Image at mouse location using jQuery.
See this demo

You can easily get the X and Y coordinates on an element such as an image at the precise mouse location using jQuery. You can either move the mouse over an image and get the location (coordinates) or click the mouse at any point on the image and get its coordinates.

I’ll show you can show a text or some message at the precise location of the mouse click on an image.

The Script and Markup

You can dynamically show and position the <div> element (with some text) using the <img /> elements X and Y coordinates like this.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
    <p>Click anywhere on the image to show a text at the precise mouse click location.</p>

    <div>
        <img id="img01" src="https://www.encodedna.com/images/theme/easy-image-resizer.jpg" />
    </div>
    <div id="divIntro" style="width:auto;display:none;"></div>
</body>

<script>
    $(document).ready(function () {
        $('#img01').click(function (e) {
            $('#divIntro')
                .show()
                .text('At location - X: ' + e.pageX + ' Y:' + e.pageY)
                .css({ position: 'absolute', color: '#000',
                    left: e.pageX, top: e.pageY
            });
        });
    });
</script>
</html>
Try it

This is how you can get the coordinates or location of the mouse and place a text at the location. However, make sure the elements position (the <div> in the case) is set as absolute.

Similarly, you can track the mouse coordinates over an image while hovering or moving the mouse. To do this, you can use jQuery on() method with mousemove property. For example,

<script>
    $(document).ready(function () {
        $('#img01').on('mousemove', function (e) {
            $('#divIntro')
                .show()
                .text('At location - X: ' + e.pageX + ' Y:' + e.pageY)
                .css({ position: 'absolute', color: '#000',
                    left: e.pageX, top: e.pageY
                });
        });
    });
</script>
See this demo

← PreviousNext →