Home > Blockchain >  Animate div towards mouse coordinates using JavaScript on click
Animate div towards mouse coordinates using JavaScript on click

Time:12-28

I am trying to get the ball element to both move and shrink towards the goals on mouse click. I have created a function that grabs the coordinates of the mouse click in the goals, however I have been struggling with the ball animation.

I thought about using keyframes, but I don't know how to use keyframes in JavaScript. I also tried doing a transform - which I know wouldn't work, but tried as you can see in the move() function.

This is my javascript/html file

    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" >
                    <div id="goals"  onclick="goal()">
        
                    </div>
                    <div id="goalkeeper" onclick="save()">
                    </div>
        
                    <div id="kick-off">
                        <div id="ball" >
                        </div>
                    </div>
        
                    <div id="score-container">
                        <div id="counter">
                            <h1 >Score</h1>
                            <h1  id="score">0</h1>
                        </div>    
                    </div>
                </div>
                
                <script src='js/script.js'></script>
        </BODY>

Just in case, this is my canvas/UI enter image description here

CodePudding user response:

If you are looking for something like this:

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

document.addEventListener("click", (e)=>{
  console.log(e)
  div.style.top = e.clientY   "px";
  div.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>

Just give the ball position absolute, and on every click event change the top and the left of the ball with javascript.

  • Related