How to get coordinates of a mouse click in Vue.js and JavaScript?

Sometimes, we want to get coordinates of a mouse click in Vue.js and JavaScript.

In this article, we’ll look at how to get coordinates of a mouse click in Vue.js and JavaScript.

How to get coordinates of a mouse click in Vue.js and JavaScript?

To get coordinates of a mouse click in Vue.js and JavaScript, we can use get the properties of the mouse click event object.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and app container.

Then we write:

const v = new Vue({
  el: '#app',
  template: `
    <div @click='onClick'>
    	click me
    </div>
  `,
  methods: {
    onClick(e) {
      console.log(event.clientX);
      console.log(event.clientY);
      
      console.log(event.pageX);
      console.log(event.pageY);
      
      console.log(event.screenX);
      console.log(event.screenY);
    }
  }
})

to add a div with a click handler.

When we click the div, onClick is run.

Then from the e parameter of onClick, we get the position of the click in various ways.

clientX and clientY give the coordinates of the mouse relative to the viewport in CSS pixels.

pageX and pageY give the coordinates of the mouse relative to the <html> element in CSS pixels.

screenX and screenY give the coordinates of the mouse relative to the screen in device pixels.

Conclusion

To get coordinates of a mouse click in Vue.js and JavaScript, we can use get the properties of the mouse click event object.