Locate the exact cursor position upon user click and showcase a div at the same spot

I am seeking a solution to determine the exact position of the cursor where a user has clicked.

My goal is to display a div at the bottom side of the page wherever the user clicks.

For instance, on the Stack Overflow homepage, if someone clicks on the logo, the div should appear at the bottom position of the logo.

Similarly, if I click on a link at the bottom of the page, the div should be displayed at that same location.

While I am currently using mootools as my JS framework, any JavaScript code would be appreciated for this task.

I hope this explanation clarifies my query.

Thank you in advance,
Avinash

Answer №1

<head>
</script>        
function getXPosition(evt) 
{
    if (evt.pageX) return evt.pageX;
    else if (evt.clientX)
        return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    else return null;
}
function getYPosition(evt) 
{
    if (evt.pageY) return evt.pageY;
    else if (evt.clientY)
        return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop :  document.body.scrollTop);
    else return null;
}
function handleClickedEvent(evt)
{
    if(typeof evt == 'undefined')
    evt = window.event;
    alert("X = "+ getXPosition(evt) + " Y= " + getYPosition(evt);

}
</script></head>
<body onclick="handleClickedEvent()"></body>

You can also use window.event.x, window.event.y but this method is more stable and reliable for getting positions.

[ Instead of using the alert message, you can update the

divElement.style.left ,  divElement.style.top
based on the x and y positions. Make sure the div's position(in style) is set to absolute. ]

Answer №2

Utilizing the prototype is quite straightforward:

document.observe('click', function(e) {
    $('YourDivId').setStyle({
        'left': e.clientX, 
        'top': e.clientY
    }).show();
});

To implement this functionality, simply create an HTML DIV within your body with the CSS properties "display: none" and "position: absolute;", along with the desired content.

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

Python and Javascript clashing with one another

(Updated question for clarity). I am currently developing a flask app game that involves users inputting guesses via the web browser. The backend, which runs on Python, checks these guesses and provides feedback to the user about their accuracy. Additional ...

How to Avoid Duplicating Documents in MongoDB?

I'm currently exploring effective methods to avoid saving duplicate documents in MongoDB. Currently, my form captures the user's URL input. The workflow is as follows: Validate if the user's URL is valid (using dns.lookup). If the use ...

Initiating and handling a POST request

In my node.js server, I have a simple setup like this: var express = require('express'); var app = express(); app.post('/savearticles', function (req, res) { res.send(req.body); }); Additionally, the javascript code is not very c ...

Struggling with jQuery UI Draggable 1.10.3 bug in Firefox: Cursor center not detected when scrolling window

Before version 1.10.3, possibly 1.9.x, I didn't encounter this issue. However, after updating to jQuery UI 1.10.3, Firefox seems to have trouble locating the center of the cursor on the draggable plugin when the window is scrolled down. This problem ...

Inoperable await statement within a while loop

Here is my code snippet for the app: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); async function init() { while (true) { console.log("TICK"); await (rl.qu ...

The error "Unable to create an instance of mssql.Schema" indicates that the

Seeking assistance from experienced ReactJS developers to address the issue outlined below. The code provided is based on a tutorial I was following. Despite numerous attempts, I have been unable to resolve the issue. Here is the code snippet from User.js ...

Having difficulty retrieving the initial selection value

Despite receiving all other values, I am unable to retrieve the event.everyday value. Can you please help me identify what I might be doing incorrectly? Situation - Choose Every day from the dropdown menu. Click on the "click it" button and review the ...

Is it true that Redux Saga's select function returns mutable state?

Is the state returned by Redux Saga's select function mutable or immutable? To learn more, visit https://github.com/redux-saga/redux-saga ...

Steps for integrating a valid SSL certificate into a Reactjs application

After completing my ReactJS app for my website, I am now ready to launch it in production mode. The only hurdle I face is getting it to work under https mode. This app was developed using create-react-app in a local environment and has since been deployed ...

Utilize datetime values in chartjs ajax for data visualization

I'm currently working on creating a chart using chart.js. I have php code that retrieves datetime data through an ajax call. However, the chart is not displaying any data and there are no visible errors. I've checked the php code using console.lo ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Animate hovering over a specific element within a group of similar elements using jQuery

Hi there! I recently started exploring Js and jQuery, and I was able to create a cool width change animation on a div when hovering over another. However, I ran into an issue when trying to implement this with multiple sets of similar divs. Whenever I hove ...

Implementing a scrolling text feature in React

I have a unique requirement for my text to be displayed once I am 100px above it, and to remain hidden before reaching that point. Additionally, I want the text to slide in from the left once it hits that 100px mark. This is a new challenge for me, as I ha ...

When attempting to update a task with the Microsoft Graph API, the server returned a 400 error code

Attempting to update a Task using the Graph API from an angular2 typescript app. Here is an example of my request - Request URL:https://graph.microsoft.com/beta/tasks/_1EKXXuN1UGInJ9yVHAjIpYAKuC2 Request Method:PATCH Request Body: { "createdBy":"f16 ...

Is MongoDB caching its collection in memory?

Utilizing mongoDB for storing a set of polygons and executing $geoIntersects queries to determine the polygon containing a specific point. My mongoose Schema is structured as follows: var LocationShema = mongoose.Schema({ name: String, geo: { ...

When items are removed client-side, the Listbox becomes null

Given a Web Forms project inherited by me, I am relatively new to the field of Web development. The page in question features 2 listboxes: lstCaseLoad, containing "Caseloads" (ID numbers), and lstAssignedCaseLoad, filled with Caseloads chosen by the Form U ...

What is the best way to create a full bleed background image that adjusts to different screen resolutions using CSS and JavaScript?

Similar Question: Full Screen Background Image in Firefox Check out: Is there a way to achieve a similar effect on a website where the content adjusts to different monitor resolutions? On the Ingress site, it seems like everything scales proportional ...

Progress of file uploads on the client side using Vue JS

I'm facing a challenge in creating a loading bar that shows the progress when a file is selected for upload in a form. Most of the examples I come across online demonstrate the loading bar after hitting an 'upload' button, but in my case, I ...

Generating exportable dynamic code in Javascript

Any assistance or links to similar inquiries would be greatly welcomed as I have conducted some research but am uncertain about the best approach to take in this situation. I find it difficult to articulate exactly what I need, so I have created a visual ...

Enable the click functionality for a disabled MI TextField

I'm utilizing a disabled TextField in my project and updating it using React Hooks useState to modify the value property of the TextField. const [employee , setEmployee] = React.useState('') <TextField fullWidth ...