Issue with mouse movement causing inaccurate coordinates

Hello there! I am facing an issue with a small project I'm working on. My goal is to have an indicator appear whenever I hover my mouse over the fishing area, but it seems like the coordinates are off when using the mousemove event. You can check out my code on this link.

HTML

<div class="game-content">
      <div class="pond">
        <div id="circle" class="circle"></div>
        <div id="pond__fishing-area" class="pond__fishing-area"></div>
      </div>
    </div>
    

JS

new Vue({
      el: '#app',
      mounted() {
        let circle = document.getElementById("circle");
        let circleRect = circle.getBoundingClientRect();
        let wrapper = document.getElementById("pond__fishing-area");
        let wrapperRect = wrapper.getBoundingClientRect();

        function moveCircle(e) {
          gsap.to(circle, 0.3, {
            css: {
              left: e.clientX,
              top: e.clientY
            }
          });
        }
        wrapper.addEventListener("mouseover", function() {
          gsap.to(circle, 0.4, { scale: 1, autoAlpha: 1 });
          wrapper.addEventListener("mousemove", moveCircle);
        });

        wrapper.addEventListener("mouseout", function() {
          gsap.to(circle, 0.4, { scale: 0.1, autoAlpha: 0 });
        });
      }
    })
    

Answer №1

Seeing that the pond is positioned in a relative manner, it is causing the circle to be incorrectly positioned when using the moveCircle() function. To ensure the circle is positioned correctly, we should make it relative to the pond's position. This means subtracting the pond's position from the client's position. The updated moveCircle() function would appear like this:

function moveCircle(e) {
        let position=document.getElementById("circle").parentElement.getBoundingClientRect();
// position will contain the position of pond
          gsap.to(circle, 1, {
            css: {
              left: e.clientX-position.x,// giving relative position to circle
              top: e.clientY-position.y
            }
          });
        }

new Vue({
  el: '#app',
  mounted() {
    let circle = document.getElementById("circle");
    let circleRect = circle.getBoundingClientRect();
    let wrapper = document.getElementById("pond__fishing-area");
    let wrapperRect = wrapper.getBoundingClientRect();

    function moveCircle(e) {
    let position=document.getElementById("circle").parentElement.getBoundingClientRect();
// position will contain the position of pond

      gsap.to(circle, 1, {
        css: {
          left: e.clientX-position.x, // giving relative position to circle
          top: e.clientY-position.y
        }
      });
    }
    wrapper.addEventListener("mouseover", function() {
      gsap.to(circle, 0.4, { scale: 1, autoAlpha: 1 });
      wrapper.addEventListener("mousemove", moveCircle);
    });

    wrapper.addEventListener("mouseout", function() {
      gsap.to(circle, 0.4, { scale: 0.1, autoAlpha: 0 });
    });
  }
})
@import url("https://fonts.googleapis.com/css?family=Roboto&display=swap");
* {
  font-family: 'Roboto', sans-serif;
}

.game-content {
  display: -webkit-box;
  display: flex;
  -webkit-box-pack: center;
          justify-content: center;
  width: 100%;
  height: 100%;
}
.game-content .circle {
  height: 50px;
  width: 50px;
  background-color: red;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
  position: absolute;
  z-index: 3;
  pointer-events:none;
}
.game-content .pond {
  width: 700px;
  height: 400px;
  background-color: #fff;
  display: -webkit-box;
  display: flex;
  -webkit-box-pack: center;
          justify-content: center;
          position:relative;
}
.game-content .pond .pond__fishing-area {
  position: absolute;
  width: 600px;
  height: 200px;
  background: blue;
  bottom: 20px;
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.0.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="game-content">
    <div class="pond">
      <div id="circle" class="circle"></div>
      <div id="pond__fishing-area" class="pond__fishing-area"></div>
    </div>
  </div>

Answer №2

According to the suggestion by @hasan05, follow these steps to resolve the problem:

  • In the .pond class, delete the line position: relative;
  • In the .circle class, include pointer-events: none;

Answer №3

When the css attributes of your pond are set to position: relative, it may be causing incorrect coordinates. It is recommended to remove this setting.

Answer №4

position: relative; is causing inaccurate calculations.

We need to find a different approach and eliminate this issue.

Additionally, let's update the following event code:


wrapper.addEventListener("mouseout", function(event) {
var targetElement = event.toElement || event.relatedTarget;
if(targetElement == circle) {
return;
}
gsap.to(circle, 0.4, { scale: 0.1, autoAlpha: 0 });
});

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

Managing repeated calls to a specific get function in nodejs

Utilizing an Ajax call, I am invoking the following GET function every 10 seconds to monitor the status of various URLs. app.get('/getUrl', function(req, res) { var response = {}; var keyArr = []; var urlData ...

Steps for retrieving the identifier of a duplicated element

I've copied an element and changed their IDs, but I'm having trouble fetching the IDs of the cloned elements in jQuery. Can someone assist me with this issue? The HTML view source code is provided below: <table id="dataTable" borde ...

Eradicate white space in a JavaScript code

Calling all JS programmers! Here's a challenge for you, check out this demo: https://codepen.io/gschier/pen/jkivt I'm looking to tweak 'The pen is simple.' to be 'The pen issimple.' by removing the extra space after 'is& ...

Removing a Button from a Form Using JavaScript

Here is a snippet of my HTML code: <form id="form"> <input id="deleteNumber" name="del" type="hidden" /> <input id="addAddress" name="addAddress" type="hidden" /> ... ... ... <a href="javascript:deleteAddress();" class="deleteItem" ...

Is it possible to utilize a designated alias for an imported module when utilizing dot notation for exported names?

In a React application, I encountered an issue with imports and exports. I have a file where I import modules like this: import * as cArrayList from './ClassArrayList' import * as mCalc1 from './moduleCalc1' And then export them like t ...

Error message: jQuery AJAX request fails due to permission denial issue on Internet Explorer

I am facing a major challenge on my website. I have implemented AJAX to update the content of a DIV, which works perfectly on all pages except for some links under the Portfolio tab. The links for "photography", "interactive", "print", and "traditional" tr ...

Children divs unexpectedly showing up outside of their parent divs

I have reviewed similar questions on this matter, but none of them seem to provide a solution for the issue I am facing. Currently, my goal is to display a stylized list, but I am encountering more difficulties than expected. You can find a fiddle linked ...

Is your React conditional rendering malfunctioning due to state issues?

I am attempting to create a component that will only be displayed after clicking on a search button. Below is the current code that I have: Update After making some changes, I am now encountering this error: Error: ERROR in /home/holborn/Documents/Work ...

Private route displaying unexpected behavior when making API call

A snippet of code I have been working on is partially functioning (refer to the last paragraph for a detailed description): App.Js: export default function App() { const [isLoggedIn, setisLoggedIn] = useState(null); const logIn = () => { setisLogg ...

Can Chrome Support Bookmarklets?

While attempting to craft a bookmarklet in Chrome using the console, I encountered the following error: Refused to load the script 'https://code.jquery.com/jquery-1.6.1.min.js' because it violates the following Content Security Policy directive: ...

Eliminating unique phrases from text fields or content sections with the help of jQuery or JavaScript

I'm currently working on a PHP website and have been tasked with the responsibility of removing certain special strings such as phone numbers, email addresses, Facebook addresses, etc. from a textarea that users input data into. My goal is to be able ...

When coding on Github pages, the behavior of code blocks can vary depending on whether

I am interested in obtaining the offline version, which can be seen here: https://i.sstatic.net/NKFSQ.jpg On the other hand, the online version has a different appearance: https://i.sstatic.net/133gH.jpg If you want to view the incorrect version, click ...

What is the method for altering font color in HTML?

Here is the section of my code that I am struggling with: <p style="font-family:'impact', color:red"> something </p> The issue I am facing is that I am unable to use both the color and the font propert ...

Unable to locate the tag using .find() function following the use of .attr() method

I am currently utilizing jQuery in conjunction with node-horseman to interact with a specific page. My approach involves referencing the page's data-id attribute, which I then pass to my application to search for the li element containing this attribu ...

Ways to adjust the distance between logo and slider

I am using this script to showcase some products. You can find the script at: http://tympanus.net/Tutorials/ItemSlider/ When resizing the web browser from maximum size to smaller, I find that the height between the logo and shoes is too large for my likin ...

Issue arises when annotation is utilized in ChartJs, as the tooltip fails to appear

Upon hovering over a dot, only a blue line is displayed without showing a tooltip as expected below: Library Version: "chart.js": "^2.9.3", "chartjs-plugin-annotation": "^0.5.7" Actual : enter image descriptio ...

Is it recommended to continue using vendor prefixes for border-radius property?

When coding, I currently utilize the following: -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; After running tests, it seems that there was no noticeable difference in modern browsers (Chrome 33+, Opera 25+, Safari 8+). Internet ...

changing the color of arrows in Vue Slick Carousel: a simple guide

I am currently using the vue-slick-carousel plugin for a carousel feature in my project. I am trying to customize the color of the arrows without modifying the default styles provided by the package itself. However, the code snippet I added to the main C ...

Utilizing jQuery to correspond with CSS media queries

Continuing from my previous question about an automatic jQuery image slider, you can refer to it here. I have made some changes in my CSS using media queries and I am trying to incorporate them into my JavaScript code using an 'if / else if' sta ...

Combining Objects in an Array using Node.js: A Step-by-Step Guide

I am working with Node.js and have 3 different sets of data. The first set contains: [ { "userId":"54c7f3ef-64d4-40de-8100-d2ec81e8aaf3", "dailyData":159392.235451, "dailyDataInUSC":255.28 ...