"Move a div towards the mouse's location by animating it with JavaScript when

I've been working on making the ball element move and shrink towards the goals upon mouse click. I successfully created a function that captures the mouse click coordinates in the goals, but I'm facing challenges with the ball animation.

I considered using keyframes for the animation, but I'm unsure how to implement keyframes in JavaScript. I also attempted a transform approach, although I knew it wouldn't work, as you can see in the move() function.

Below is my code in javascript/html:

    function goal(){   
        var score = getScore();
        increaseDifficulty(score)
        document.getElementById("score").innerHTML = score + 1 ;
        var b = getShotCordinates();
        move(b[0],b[1]);
    }
    
    function save(){
        resetScore();
    }
    
    function resetScore(){
        document.getElementById("score").innerHTML = 0;
    }
    
    function getScore(){
        return parseInt(document.getElementById("score").innerHTML);
    }
    
    function move(x,y){
        const fxMove = `translate(${x}px, ${y}px);`;
        const fxAnim = `transition: transform 0.5s; transform: translate(0, 0);`;
        document.getElementById("ball").style.transform = translate(x,y); 
    }
       
    function getShotCordinates(){
        var e = window.event;
        var Cordinates = [e.clientX, e.clientY];
        console.log(Cordinates[0] + " - " + Cordinates[1])
        return Cordinates;
    }
        <BODY>
                <div id="canvas" class="field">
                    <div id="goals" class="goals" onclick="goal()">
        
                    </div>
                    <div id="goalkeeper" onclick="save()">
                    </div>
        
                    <div id="kick-off">
                        <div id="ball" class="ball">
                        </div>
                    </div>

                    <div id="score-container">
                        <div id="counter">
                            <h1 class="counter-text">Score</h1>
                            <h1 class="counter-score" id="score">0</h1>
                        </div>    
                    </div>
                </div>
                
                <script src='js/script.js'></script>
        </BODY>

For reference, here's a link to view my canvas/UI: https://i.sstatic.net/JWol4.png

Answer №1

Are you in search of code similar to the one below?

const box = document.querySelector("div");

document.addEventListener("click", (e)=>{
  console.log(e)
  box.style.top = e.clientY + "px";
  box.style.left = e.clientX + "px";
  
})
div{
  width:50px;
  height:50px;
  background:red;
  border-radius:50%;
  position:absolute;
  transition:.3s;
  transform:translate(-50%, -50%);
}
<div></div>

To achieve this effect, simply assign the ball a position of absolute and use JavaScript to update its top and left positions on every click event.

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

Adding elements to a JSON array in Javascript

Seeking assistance on updating a JSON array. var updatedData = { updatedValues: [{a:0,b:0}]}; updatedData.updatedValues.push({c:0}); This will result in: {updatedValues: [{a: 0, b: 0}, {c: 0}]} How can I modify the code so that "c" becomes part of ...

Having trouble retrieving cell values from a table using tr and td tags in C# Selenium is causing issues

I'm facing an issue where my code is unable to retrieve the cell value and instead throws an exception stating: "no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div[2]/div[2]/table/tr[1]/td[0]}" Below is the HTML ma ...

How can I locate the quantity of items within an embedded document in MongoDB?

Examining my schema, it appears like this: name: value: p_vars: { name1: {}, name2: {}, } My goal is to determine the number of items in p_vars. Assuming the interpreter is JavaScript, I attempted the following: db.collection.findOne().p_vars.l ...

Leveraging grunt-develop

I have recently developed a basic NodeJS + Express application that runs smoothly when I use the command node app.js. However, my current task is to incorporate grunt-develop into my project. Here is how I configured it: grunt.initConfig({ develop: { ...

Make the navigation bar stay at the top of the page when scrolling past another element with a top position of 100vh

Trying to explain a unique concept here. I want a nav bar fixed in the position of top:100vh, so that as I scroll down and reach the next section, the navbar sticks at the top rather than staying stuck at the beginning with position:fixed top:0. The aim is ...

Animate CSS backward when hovered

I am having trouble with getting an animation to play in reverse when hovering over an element. No matter what I try, it just snaps back to the beginning without any smooth transition. Interestingly, this issue only occurs in Chrome and Safari browsers. ...

Tips for validating forms using jQuery

Upon form submission, an alert is displayed before redirecting to a new page. I have implemented a function that triggers on button click. The alert will appear first, followed by the form submission. I would appreciate ideas on how to validate the form. ...

Create an Oval-Shaped Image Cutout

Currently, I have a fabric.JS canvas where objects can be added. However, I am interested in clipping these objects into an oval shape, similar to the clip demos on fabricjs.com. In my current project (JSFiddle), I have been able to crop the object into a ...

Utilize Chrome storage instead of localstorage to generate Parse sessions

I'm currently developing a Chrome Extension that relies on Parse User sessions. Because localstorage is limited to specific domains, I am looking to utilize chrome.storage so the data can be accessed across any site. The existing Parse Javascript SDK ...

Enhancing visual appeal with Carousel Slider images

I am facing an issue with the Carousel Slider. I added an image to index.php, but when I tried adding a second image, it appeared just below the first one in the carousel. Click here for the first image Click here for the second image Slider.php < ...

Ensuring jQuery ajax requests can still be made when clicking on various links

After successfully creating code for ajax requests and fetching information from the server, I encountered an issue where clicking a link would smoothly transition me to a new page without refreshing the header and footer. However, upon clicking another li ...

Modify the parent scope variable within an Angular directive that contains an isolated scope

Here is a directive implementation: <some-directive key="123"></some-directive> This directive code looks like this: angular.module('app').directive('someDirective', ['someFactory', '$compile', '$ ...

developing a sleek visual transition using CSS animation

Have you seen the awesome animation on Discord's website? Check it out here! The way those coins move up and down so smoothly is really impressive. How can I recreate that effect for my own images? I decided to start with this code snippet img { ...

Issue encountered while deploying Next.js application on vercel using the replaceAll function

Encountering an error during deployment of a next.js app to Vercel, although local builds are functioning normally. The issue seems to be related to the [replaceAll][1] function The error message received is as follows: Error occurred prerendering page &q ...

What is the best way to access data stored in the state of the store.js within a Vue application?

Currently, I am working on my initial project using Vue.js. The application involves a multi-step form that shares a common header and footer. As the user progresses through each step, the data entered is sent to store.js for storage. However, I have encou ...

How to retrieve the output of a nested function in Node.js

I have been attempting to retrieve a value from a function nested inside another function in my Node.js application, but it always seems to return undefined. var geo = { list: function(callback){ var returnval; gapi.getcodes(function(e ...

The problem with "em" in CSS: preventing it from scaling based on the font-size of a particular element

My website predominantly utilizes "em" for design over "px," which is meant to be more compatible with modern browsers. Most of the text is set at font-size:1em, where 1em equals 16px as a default without specific specification. However, there are sectio ...

A guide to adding a picture to AWS S3 with the help of GraphQL

When trying to upload a base64 string via GraphQL, I encountered an issue. It seems that if the string exceeds 50,000 characters, GraphQL fails to reach the resolve function without giving any error messages. However, when the string is less than 50,000 ...

My ReactNative Android application is experiencing significant lag, is there anyone who can assist me in resolving this issue?

Currently, I'm tackling a reactnative android app project and have noticed a significant drop in performance. Unfortunately, I am clueless about the root cause of this issue. Could it be related to the navigator or are there other underlying factors a ...

Leveraging the power of Framer Motion in combination with Typescript

While utilizing Framer Motion with TypeScript, I found myself pondering if there is a method to ensure that variants are typesafe for improved autocomplete and reduced mistakes. Additionally, I was exploring the custom prop for handling custom data and des ...