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

Say goodbye to <!DOCTYPE html> when using htmlAgilityPack

I'm currently developing an app for WP 8.1, and one of the tasks I need to accomplish is parsing a webpage with the following structure: <!DOCTYPE html> <html> <body> <table cellspacing="0" cellpadding="0" border="0" style="b ...

enhancing look of external tool

I have a third-party widget with inline CSS that displays a table on my website. Is there a way to strip out the inline CSS from the widget before adding it to my page so that only my custom css file styles are applied? The HTML structure of the widget i ...

Error: The constructor for JsSHA is not valid for the TOTP generator

Attempting to create a TOTP generator similar to Google's timed-based authenticator using the React framework. I am utilizing the bellstrand module for TOTP generation, but I am encountering issues when trying to import it into my React code. Here is ...

Applying a variety of elements to a single function

I am in the process of creating a mini-survey and I want the buttons to change color when clicked, but return to normal when another button is selected within the same question. Currently, clicking on a button turns it red while leaving the others clear. H ...

Display a loading screen to the user while Vue lazy loads the content

I am currently implementing lazy loading features for my single-page application using Vue.js and Laravel Mix 5. I am looking for a way to display a loading page to prevent the app from appearing unresponsive while new pages are loading. I attempted to ad ...

Exploring different methods for drawing a polygon by iterating through JSON values

I am attempting to automatically draw a polygon using values stored in a database. The Python file I have returns JSON results to an AJAX call. In the AJAX success section, I need to iterate through the JSON data and automatically draw a polygon on a Googl ...

Slide both divs simultaneously from left to right

Is there a way to simultaneously hide and show div elements, without having to wait for the effect to take place? Here is my current code: $('a').on('click', function(){ var div_hide = $(this).parent(); var div_show = $(this). ...

Issue with JQuery .fadeToggle() function: Unexpected behavior causing automatic fade-out

$(document).on('click', '.tree label', function(e) { $(this).next('ul').fadeToggle(); e.stopPropagation(); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul cl ...

"Embrace the power of Ajax and JSON with no regrets

function register() { hideshow('loading', 1); //error(0); $.ajax({ type: 'POST', dataType: 'json', url: 'submit.php', data: $('#regForm').serialize(), su ...

Why Chrome Doesn't Alter the State of li Elements

I'm unsure why, but the CSS code in this particular fiddle fails to function correctly on Chrome. On Firefox, when hovering over one of the li elements, the text becomes visible as expected, whereas this does not occur on Chrome. It seems that changin ...

The drop-down arrow in the <select> element seems determined to stay within the container

I am currently exploring alternative solutions (without the use of JavaScript) to address a Firefox bug that prevents styling the dropdown arrow in select elements. Some sources suggest placing the select element within a container and adjusting the contai ...

Assigning alphanumeric characters to the axis for identification purposes

review the code in index.html <!DOCTYPE html> <html> <head> <title>D3 test</title> <style> .grid .tick { stroke: lightgrey; opacity: 0.7; } .grid path { stroke-width: 0; } .ch ...

Is there a way to stop TD from going to the next line?

I am using Javascript to dynamically generate a table and I want it to extend beyond the boundaries of the page. When I manually create the table, it works fine and extends off the page, but once I put it into a loop, the <td> elements wrap onto a se ...

The Jssor bullet navigator is not visible on the webpage

Currently, I am working on implementing a full-width slider with arrow navigators, bullet navigators, and captions using the Jssor plugin. Rather than copying and pasting example code, I decided to tackle this project independently with just a little guida ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

Executing tasks in a job on GitHub using Node.JS and .NET

I am currently in the process of developing a JavaScript API for a .NET project. In order to streamline my workflow, I would like to know if it is feasible to have GitHub actions set up with both Node.JS and various versions of .NET Core (2.1, 2.2, 3.0 or ...

A horizontal navigation bar featuring a centrally aligned vertical layout and full-height display

I want to align everything on my menu bar vertically in the center, with the a elements taking up 100% of the available height of the menubar (text would be vertically-centered). However, I do not want to fix the height of my menu bar. (If I were to fix th ...

Tips for storing unique values in an object using JavaScript

I need assistance with organizing my log data, which includes camera names and system IP addresses. I am trying to create an object where each unique system IP is a key, with an array of corresponding camera names as the value. Here is the code snippet I h ...

What could be causing WidgEditor, the JavaScript text editor, to fail to submit any values?

After clicking submit and attempting to retrieve text from the textarea, I am encountering a problem where the text appears blank. The reason for this issue eludes me. function textSubmit() { var text = $("#noise").val(); console.log(text); consol ...

Attempting to transform HTML code received from the server into an image, but encountering an error while using ReactJS

This app is designed to automate the process of creating social media posts. I have a template for the vertical "Cablgram" stored in the backend, and when I make a request, it returns the HTML code for that template. However, I encounter an error when tryi ...