Why won't my picture track the movement of the cursor?

I am trying to make my image follow the cursor using a specific code, but it doesn't seem to be working. I'm having trouble figuring out what's wrong with it.

Here is the code snippet that I'm currently using:

function followIt(e){

    var img=document.getElementById("img");

    img.style.left = e.clientX;
    img.style.top = e.clientY;

}
<!DOCTYPE html>
<html lang="de">

<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
</head>

<style>
    #img{
        box-shadow: 0px 0px 1px 1px #000000;
        width: 100px;
    }
</style>

<body id="demo_body" onmousemove="followIt(event)">
<img src="https://i.postimg.cc/g02SqdrF/followmouse.png" id="img">
</body>

<script src="script.js" text="text/javascript"></script>
</html>

Answer №1

  • To ensure your image stays in place, utilize CSS properties like position: fixed; since clientX/Y values are relative to the viewport
  • Include the missing unit of measurement "px" in your JavaScript code
  • Opt for using addEventListener() over inline event handlers with on*
  • Avoid querying the DOM within performance-heavy loops; store your element in a variable and use that reference instead

const EL_img = document.querySelector("#img");

function followIt(e) {
  EL_img.style.left = e.clientX + "px";
  EL_img.style.top  = e.clientY + "px";
  // Alternatively:
   // EL_img.style.cssText = `left: ${e.clientX}px; top: ${e.clientY}px;`;
}

window.addEventListener("mousemove", followIt);
#img{
  position: fixed;
  box-shadow: 0px 0px 1px 1px #000000;
  width: 100px;
}
<img id="img" src="https://i.postimg.cc/g02SqdrF/followmouse.png" >

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

Retrieve information from an external source and subsequently make alterations to it

If a certain external site returns a string like "cost is 10$", is it possible for me to display it as "price:10$" on my own website using only Javascript? The external site could be something like Facebook.com. My website, of course, belongs to me. Hello ...

What methods are available to gradually increase a counter until it reaches a specific number by a designated date?

I have a unique idea for my website - I want to create a special counter that gradually increases to a specific number, but does so over the course of an entire year. Imagine starting at 0 and aiming to reach 35340340 after exactly one year has passed. It ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

It is not possible to simultaneously utilize the properties `display: inline-block` and `width: 100%`

As someone with limited CSS knowledge, I have encountered a challenge. My goal is to ensure that my website's body has a width of 100%, while also preventing the content from wrapping when the browser window is resized. To achieve this, I attempted a ...

Tips for utilizing onsubmit following an ajax validation check

How can I implement the onsubmit method after an ajax check? The current onsubmit function is not working. $(document).ready(function(){ $("#p_code").change(function(){ $("#message").html("<img src='ajax_loader.gif' width='26 ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

Attempting to implement the tagify plug-in in order to automatically fill a text field with dynamic labels

I have a code snippet that acts as an event listener for checkboxes inside a dialog box. It allows me to populate or de-populate a text field with values from the checkboxes by checking or unchecking them individually. // Event listener which selects indi ...

When adding an object to an array in AngularJS, it seems to trigger updates for

Currently, I am fetching data from a WebAPI and then storing it in an array called products, which is scoped. $scope.products In addition to the products array, I also have another scoped array named selectedFish. $scope.selectedFish = []; My objective ...

If I change the request mode to 'no-cors' in my Firebase cloud function, how will it impact the outcome?

After encountering an issue with the Firebase inbuilt password reset functionality, I created a Firebase function to handle OTP verification and password changes based on the correctness of the OTP. The function is designed to validate the OTP provided, ch ...

Displaying various Ajax html responses

The function $('.my-button').click(function(e) is designed to display the output of the MySQL query in display.php, presented in HTML format. While it functions correctly, since each button is looped for every post, the script only works for the ...

modifying a record in MongoDB with the help of Mongoose

I need help with updating a collection in MongoDB using Mongoose. function check (db) { var hours = 60 * 60 * 1000 var threeHours = 3 * hours; var lastUpdated = null; db.collection("profile").find({userName: "Rick"}).toArray(function(er ...

Error message encountered when deploying a Discord bot on Heroku: "SyntaxError: Unexpected token '??='"

I encountered an issue when trying to deploy a Discord bot that I created using Node.js on Heroku. The error message is as follows: 2021-11-05T00:00:10.334347+00:00 app[web.1]: > node . 2021-11-05T00:00:10.334348+00:00 app[web.1]: 2021-11-05T00:00:10.3 ...

Highlighting the current menu item by comparing the URL and ID

Looking to make my navigation menu items active based on URL and ID, rather than href. None of the suggested solutions (like this one, this one, or this one) have worked for me. This is how my Navigation is designed: <nav id="PageNavigation"& ...

Is there a way to append the current path to a link that leads to another URL?

I am currently in the process of separating a website, with the English version being on the subdomain en. and the French version residing on the www. Before making this change, I have a drop-down menu that allows users to select their preferred language ...

What is the process of integrating an ejs view engine with express on Netlify?

Need help configuring the ejs view engine with netlify I attempted to set app.set('view engine', 'ejs'), but didn't see any results. const express = require('express'); const path = require('path'); const serv ...

Guide on accessing the text content within a div element in HTML by triggering a button click

To extract specific text from multiple div tags, I need to trigger an event when clicking a button. <div class="col-lg-3 col-md-6 mb-4"> <div class="pricing-table pricing-secondary"> <div class="price-hea ...

Conceal a division based on its numerical position

I'm having trouble figuring out how to hide multiple divs based on an index that I receive. The code snippet below hides only the first div with the id "medicalCard", but there could be more than one div with this id. document.getElementById("medical ...

What are the possible arguments for the event type onInput?

While diving into the world of html / javascript / vue, I stumbled upon the following code snippet. <input type="text" onInput="doAction(event);"> <script> var mesdata = { message: 'type your m ...

Text area capacity

Is there a limit to the maximum capacity of a textarea for accepting text? The HTML page functions correctly when the text is limited to around 130-140 words. However, if the text exceeds this limit, it causes the page to hang without any response. The tex ...

Fixing alignment and responsiveness problems with a hovering circle div

I have 3 circular divs that resize slightly when you hover over them, but this resizing also occurs if you hover near them. Additionally, I want them to be centered with some responsive spacing. Here is a live demo: demo Below is my code: <div id ...