Show a Text over an Image at Mouse Location using jQuery

Show a Text over an Image at Mouse Location using jQuery

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.

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

Well, that’s it.

Previous - Export HTML Table to Excel using jQuery table2excel Plug-inNext - How to Set or Assign Value to a Label dynamically using jQuery



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!