Mouse Coordinates | Mouse Move | Get Mouse Position In Javascript







Mouse Coordinates | Mouse Move | Get Mouse Position In Javascript

Welcome🎉 to Code With Random blog. In this blog, we learn how we create a Mouse Coordinate. We use HTML, Css, and javascript for this Mouse Coordinates. I hope you enjoy our blog so let’s start with a basic HTML structure for the Mouse Coordinates.

HTML Code

 <div class = "container">  
<h5 class = "mainText">🖱️ Coordinates of your mouse: <br> hover over this container </h5>
</div>

There is all the HTML code for the Mouse Coordinates. Now, you can see an output with Mouse Coordinates then we write javascript for the Mouse Coordinates.

output

Mouse Coordinates | Mouse Move | Get Mouse Position In Javascript

CSS code

 html{  
overflow-y: hidden;
}
.container {
width: 80vw;
height: 80vh;
background: rgba(20,20,20,0.5);
margin:5% auto;
border-radius: 20px;
border: 10px solid black;
}
.mainText{
pointer-events: none;
font-family: 'Roboto Condensed';
sans-serif;
color: white;
text-align: center;
font-size: 280%;
margin: 25vh 18vw;
}

Css Updated output

Mouse Coordinates | Mouse Move | Get Mouse Position In Javascript

Javascript code

 const text = document.querySelector('.mainText');  
const mainContainer = document.querySelector('.container');
mainContainer.addEventListener("mousemove", runEvent);
//event handler
function runEvent(e){
e.preventDefault();
//print Coordinates of the mouse on move on the targeted element:
text.textContent = `MouseX: ${e.offsetX}, MouseY: ${e.offsetY}`;
//change body background color taking the coordinates as values of rgb:
document.body.style.backgroundColor = `rgb(${e.offsetX}, 180, ${e.offsetY})`;
}

Final output

Mouse Coordinates | Mouse Move | Get Mouse Position In Javascript

Now that we have completed our javascript section,  Here is our updated output with javascriptHope you like the Mouse Coordinates. you can see the output video and project screenshots. See our other blogs and gain knowledge in front-end development. Thank you 🙏💕!

In this post, we learn how to create a Mouse Coordinates using simple HTML & CSS, and javascript. If we made a mistake or any confusion, please drop a comment to reply or help you in easy learning. 

Written by – Code With Random/Anki 

Code by – Elena

Share on:

Leave a Comment