Open In App

Vue.js Mouse Tracker Example

In this article, we will demonstrate the way to track a mouse position in Vue js. In JavaScript, we have methods that help us to capture the location of the mouse on the screen. The top left corner of the screen is (0, 0) i,e, X, and Y coordinates are (0, 0). This means that vertical zero is the topmost point and horizontal zero is the leftmost point. JavaScript provides “clientX” and “clientY” properties to track the mouse pointer in the current window. These properties find out where the user’s mouse lies in the x and y coordinates of the browser window.

Steps for Installation & Configuration

Step 1: Make sure you have an up-to-date version of Node.js installed and your current working directory is the one where you intend to create a project. Run the following command in your command line



npm create vue@latest

Step 2: After creating your Vue project move into the folder to perform different operations

cd <your-project-name>

Step to run the application: Open the terminal and type the following command.



npm install
npm run dev

Open your browser. Open a tab with localhost running (http://localhost:5173/).

Project Structure

After running the commands (mentioned in the above steps), if you open the project in an editor, you can see a similar project structure (as shown below).

project structure

Example: This example demonstrates the  Mouse Tracker in Vue.js. In App.vue, change the default code with the below code.




<template>
    <main>
        <div class="container" 
             @mousemove="handleMouseMove" 
             @mouseleave="hover = false">
            <p>Hover here</p>
        </div>
        <div v-if="hover">
            <h1>
                Mouse position is at {{ mousePosition.x }}
                {{ mousePosition.y }}
            </h1>
        </div>
    </main>
</template>
  
<script>
    import { reactive } from "vue";
  
    export default {
        data() {
            return {
                mousePosition: reactive({
                    x: 0,
                    y: 0,
                }),
                hover: false,
            };
        },
        methods: {
            handleMouseMove(event) {
                this.hover = true;
                this.mousePosition.x = event.clientX;
                this.mousePosition.y = event.clientY;
            },
        },
    };
</script>
  
<style scoped>
    .container {
        background-color: #1e2023;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 50vh;
        width: 100vh;
    }
</style>

Explanation

Please refer to the ScreenX/Y, clientX/Y, and pageX/Y article for detailed information about clientX clientY property.

Output:

 


Article Tags :