What's the process for converting offsetX and offsetY pixel coordinates to percentages?

Currently, I am working on a project where I need the offsetX and offsetY coordinates to be displayed in percentage (%) format while hovering over a div element. By default, these coordinates are shown in pixels.

Here is an example of the structure:

 <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title>Events</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <link rel="stylesheet" href="style/style.css">
      </head>
      <body>
        <div id="vue-events">
          <h1>Events in VueJS</h1>
          <div id="canvas" v-on:mousemove="updateXY">
            <img src="img/img-1.jpg" style="visibility: hidden;" />
              {{x}}, {{y}}
          </div>
        </div>
       <script src="js/events.js"></script>
      </body>
    </html>

Below is the script used for handling events:

new Vue({
      el: '#vue-events',
      methods:{
        updateXY: function(event){
           this.x = event.offsetX;
           this.y = event.offsetY;
        }
      }
    });

Answer №1

It is essential to perform the calculation independently.

Determine the window width and height and use this information to calculate the percentage. However, bear in mind that the value may vary if you resize your window.

   new Vue({
      el: '#vue-events',
      methods:{
        updateXY: function(event){
           this.x = (event.offsetX * 100) / window.innerWidth;
           this.y = (event.offsetY * 100) / window.innerHeight;
        }
      }
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to confirm that the content of two files is identical?

Currently, I am utilizing mocha/supertest/should.js for testing a REST Service. When I make a request to GET /files/<hash>, it returns the file as a stream. I am seeking guidance on how to use should.js to assert that the contents of the file are i ...

`Trouble with CSS Measurement Properties in Internet Explorer 10`

(In the past, I relied on conditional IE statements to exclude a portion of my website from IE Browsers. Unfortunately, this method is no longer supported in IE10.) Currently, I have three images displayed on the header of my site, stacked one on top of t ...

What is the best way to remove every other second and third element from an array?

I am looking to remove every second and third element of an array in Javascript. The array I am working with is as follows: var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"]; My goal is to delete every second and ...

Positioning a secondary div beside a primary div that is centered on the page

As I work on my website, I have a container that encompasses the entire design and is perfectly centered using margin:auto. Now, I am looking to float specific content to the right of this central container in a way that it stays attached to the side reg ...

Executing PHP scripts in Javascript to monitor active online users: identifies individuals who are currently not authenticated

I am currently developing a basic admin panel and looking to allow logged in users to view other active users. To achieve this functionality, I have set up a sessions MySQL table containing active session data (logged in users) alongside a PHP file that up ...

Vee-Validate: Are flags on the field value yielding undefined results? Explained with TypeScript

The documentation states that by using a flag on the value of a field, I should be able to obtain a boolean. For example: computed: { isFormDirty() { return Object.keys(this.fields).some(key => this.fields[key].dirty); } }, I am working ...

Webpack attempting to load build.js from a nested folder

I am in the process of setting up a Vue app with Vuetify and Vue Router. Everything works fine when I load the base URL "/", and I can easily navigate to /manage/products. However, if I try to directly access /manage/products by typing it into the address ...

An issue arose during the page prerendering process for "/" on Vercel | Next.js resulting in a deployment error

When attempting to deploy my website using Vercel and generating static pages, I encountered the following error in the logs: info - Generating static pages (0/6) Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/ ...

What is the significance of vendor prefixes in the world of CSS3?

While I can see the rationale behind using prefixes for experimental non-official features to avoid conflicts, what is the reason for using them on shadows and similar elements? Shouldn't all vendors be implementing effects consistently according to ...

Is there a way to turn off linting while utilizing vue-cli serve?

I am currently running my project using vue-cli by executing the following command: vue-cli-service serve --open Is there a way to stop all linting? It seems like it's re-linting every time I save, and it significantly slows down the process of ma ...

Change the content of a selectbox dynamically with the help of jQuery and AJAX

Currently, I am exploring the best approach for a specific challenge: I have various categories, subcategories, sub-subcategories, and so on, that I need to display in separate select boxes. For instance, initially, the options may look like this: <sel ...

What is the best way to cancel a request within an HTTP-interceptor?

Within an application, I have established the following URL structure for the API: // public public/url-xyz // private dashboard/url-xyz To avoid unnecessary requests, what is the most effective method for canceling a request? My current approach involv ...

Guide to creating an asynchronous function

Starting my first react website and needing assistance with writing an asynchronous JavaScript function. I am currently working on uploading user input files to firebase storage and then making a post request to the API in order to store the data in the da ...

Animating links with multi-line effects on :before.orEnhancing

As per the given query, I have a code snippet Is there any way to apply this effect to multiple lines of text instead of just one line? Currently, the effect only appears on one of two text lines (as shown in the example). :root { --00a3a3: #00a3a3; ...

Issue with RegisterClientScriptCode function following a partial postback

In a SharePoint website, the code below is contained within a user control: ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "jquery144", "<script type=\"text/javascript\" src=\"/_layouts/Unicre.Web.RUOnline.Controlos/Script ...

Having trouble retrieving information from .pipe(map()) method

Encountering some issues with Observable handling. I have a function that returns an Observable. public getData(userId) { const data = this.execute({userId: userId}); return {event: "data.get", data: data} } private execute(input: SomeDt ...

Could the absence of an external style sheet for CSS be hindering the execution of my code?

A generous Stack Overflow user provided me with the code you see here and their JSFiddle can be accessed at http://jsfiddle.net/f18513hw/. The code functions properly in JSFiddle. I copied and pasted the code into my Textpad, saved it in my htdocs folder o ...

Differentiating between inline and block elements in HTML5

Can you explain the various categories of inline and block elements in html5? I'm having trouble distinguishing between the different types of inline and block elements in html5. ...

Can you tell me the locations of the src/js and build/js directories?

Just starting out and seeking guidance. I am currently working with Node v4.2.1 and Gulp 3.9.0 on a Windows 7 machine, following along with a tutorial to familiarize myself with the task runner Gulp. I'm attempting to concatenate tasks but I seem to ...

Stacking issue - elements not properly aligned

Is there a way to move my H1 text below the blue category button instead of beside it? Thank you in advance! http://jsfiddle.net/TDBzN/ <div id="article" class="animated2 fadeInLeftBig"> <div class="article-close"></div> <div c ...