Position a div at the center of the mouse cursor using this guide

Would appreciate guidance on my goal of placing a div in the center of the mouse cursor upon clicking a link. Here's what I have so far:

<a id='btn' href='#' ><img src='test.png' /></a>

I want the new div to overlay on top of 'test.png', with the mouse cursor positioned centrally both vertically and horizontally within the div.

This is my current JavaScript setup:

var contentDiv = document.createElement('div');
var img        = document.createElement('img');

contentDiv.setAttribute('class','test1');

img.src='newimg.png';
contentDiv.appendChild(img);

$("#btn").on('click', function(e){
   $('body').append(contentDiv)
   var w = $(contentDiv).width()/2
   var h = $(contentDiv).height()/2
   var x = e.pageX - h  //- $(this).offset().left;
   var y = e.pageY - w  //- $(this).offset().top;
   $(contentDiv).css({top: y, left: x, 'transform': 'scale(.2)'})
    e.preventDefault();         
}) 

However, the code does not position the mouse cursor in the center of the new div. Any assistance would be greatly appreciated. Thank you!

Answer №1

Give it a shot

let x = e.pageX - w
let y = e.pageY - h

Check out this example

This is the jQuery approach for retrieving the mouse position (e.pageX). Alternatively, you can try:

let x = e.clientX - w;
let y = e.clientY - h;

Here's an example in pure JavaScript

This will help clarify any confusion with subtracting height from x and width from y. Remember, x represents left and right movements while y captures up and down motions. In computing, increasing x moves to the right, decreasing x goes to the left, increasing y moves down, and decreasing y shifts up.

Keep them separate and clear.

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

Is it possible to incorporate a React app as a component within a static HTML page?

Looking to integrate the react-csv-viewer component into a static HTML page without deploying it on a local server. I've tried following the instructions from the React tutorial, but am struggling with the build process. My goal is simple - to use th ...

Declaring module public type definitions for NPM in Typescript: A comprehensive guide

I have recently developed a npm package called observe-object-path, which can be found on GitHub at https://github.com/d6u/observe-object-path. This package is written in Typescript and has a build step that compiles it down to ES5 for compatibility with ...

What is the best way to utilize the JavaScript split() method to effectively split pasted text based on new lines?

Could use some assistance with this, please? I am working on contenteditable div elements and I need to enable the ability to copy and paste numbers into them. The numbers may be structured in columns and rows, similar to Excel. Upon pasting, the text sh ...

Unable to load CSS on a Sitecore platform

Currently, I am facing an issue with CSS loading on my published website while using the latest version of Sitecore 8.2. When viewing the website in Experience Editor, the carousel CSS works perfectly fine. However, once I log out and switch to the Web dat ...

Creating mobile-friendly buttons: a step-by-step guide

How can I make my button responsive? I have a button on an image within a slider. It looks good and works fine on desktop, but on mobile it appears too big and gets overlapped with the slider radio icons, causing the "read more" link button to not redirect ...

Is it possible to incorporate a NodeJS library into my React project?

I'm currently working on a project with React Typescript. My goal is to update a fillable PDF using array values upon form submission in my react form. During my research, I came across this library: https://www.npmjs.com/package/pdffiller I'm ...

Why does WebView crash when I call a Java function from my Javascript code?

Here's a perplexing issue I've encountered. Whenever I call a Java function from my Javascript code, the WebView crashes. This code is directly from the official documentation. Java: public class HelloWebView extends Activity { private W ...

I am looking to include a popover within my modal using Bootstrap version 3.0.2

Hey there, I'm having an issue where the popover that should be inside the modal is actually appearing outside of it in the top left corner, not visible within the modal itself. Below is my index code: <button type="button" id="example" class="bt ...

Ensuring Consistent Spacing Between Elements When Dealing with Varying Image Lengths

In order to clearly illustrate my need, I will provide some code here. .wrap{ display:flex; flex-direction:row; align-items: center; justify-content: flex-start; width: 100%; } .img{ width: 30px; height: 20px; background: red; } .img1{ ...

Error 404 in Cordova AJAX请求

As I work on developing an android application with cordova, AJAX requests are essential for the functionality. Utilizing jQuery for these requests, I updated the security policies in index.php to allow connection to a remote server. However, upon initiati ...

Using JavaScript to pass a value from an input field to a href attribute

I am currently working on a scenario where, upon clicking on an input field, the value is passed to a URL and the corresponding radio button is checked. This way, I can share the URL with someone else. Unfortunately, I have hit a roadblock in my progress: ...

Transferring callback functions from JavaScript to Java in Android

As I work on developing an Android app using HTML5/JavaScript, I've encountered some limitations. One challenge I face is calling a function implemented in Java code from within JavaScript, specifically to create a particular type of dialog. While the ...

Learning how to detect errors and utilize the .then() method in a single function with JavaScript

One issue I faced is that when axios encounters an error, .then() (used to display success message) doesn't work. So, I decided to include .catch() to handle errors. But how can I structure the function to both catch errors and implement .then() for s ...

Streamline JSON response codes if feasible

Is there a way to simplify this code? It seems a bit complex and messy to me. [HttpPost] public JsonResult GetUserDetails(int userId, string username) { IQueryable<Company> companies = companyRepository.GetGridCompanies(); ...

Why am I getting the "Cannot locate control by name" error in my Angular 9 application?

Currently, I am developing a "Tasks" application using Angular 9 and PHP. I encountered a Error: Cannot find control with name: <control name> issue while attempting to pre-fill the update form with existing data. Here is how the form is structured: ...

Problems with the backstack feature

I am working on my MainActivity.java class and trying to implement backstack for navigating between fragments and activity. Even after using addToBackStack(null) and popbackStack0, I am facing issues with the functionality. public class MainActivity ext ...

Discovering tags that are isolated and encasing them with specific tags

After researching Beautifulsoup, I am looking to identify <a> elements that are not nested within <p> tags and then wrap them with <p>, but I am unsure of the process <p><a href="example1.com">example1.com</a></p> ...

Cross-Origin Resource Sharing (CORS) Issue: How Angular.JS, Node.JS, and

Encountering problems retrieving data from a http post request to my API. Seeing the following error message: XMLHttpRequest cannot load (URL to API here). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Updating the image source attribute using Vue.js with TypeScript

Let's discuss an issue with the img tag: <img @error="replaceByDefaultImage" :src="urls.photos_base_url_small.jpg'"/> The replaceByDefaultImage function is defined as follows: replaceByDefaultImage(e: HTMLImageElement) ...

What could be causing the presence of additional characters in the responseText received from the Servlet to JavaScript via Ajax?

I am currently involved in a project where I am attempting to retrieve the username from a session that was created using the code below: GetCurrentUserInfo.java package servlet; import java.io.IOException; import java.io.ObjectOutputStream; import java ...