Show where the image should be placed according to the coordinates of the mouse click

My project begins with a blank canvas, prompting the user to click anywhere on the page to reveal an image. My goal is to show an image at the exact location where the user clicks. Although I can successfully trigger an image to appear in the corner of the window upon any click, I am struggling to match the coordinates of the click with the placement of the image. Currently, when a user clicks within the window, an image of a snowball pops up in the upper left corner along with displaying the x-coordinate of the click. Each subsequent click changes the displayed x-coordinate. How can I adjust my code to make the snowball appear at the click coordinates?

<head>
<script>
    document.onclick = userClicked;
    function userClicked() {

        var x = event.clientX;
        var y = event.clientY;
        document.getElementById("xCoord").innerHTML=x;
        document.getElementById("snowballAppear").style.display = '';
    }

</script>

<div class "container">
    <div class "picture">
        <img alt="snowballAppear" id="snowballAppear" style="display: none" src="http://vignette3.wikia.nocookie.net/pottermore/images/9/99/Snowball-lrg.png/revision/latest?cb=20130412122815"/>
    </div>
</div>

</head>

Answer №1

To position an image using CSS, use the "left" property for X and the "top" property for Y. Remember to include a "position: absolute;" style in the image.

Here's how you can do it in code:

function moveImage() {
    var x = event.clientX;
    var y = event.clientY;
    var snowball = document.getElementById("snowballAppear");
    snowball.style.display = '';
    snowball.style.position = 'absolute';
    snowball.style.left = x + 'px';
    snowball.style.top = y + 'px';
}

Checkout this JSFiddle for a live demo: https://jsfiddle.net/mxq629ng/

If you want to center the image around the mouse pointer, consider subtracting half of its height and width from the X and Y coordinates.

Additional tip: To ensure compatibility with different browsers, pass the "event" as an argument in the function. This will make your code work smoothly across various platforms. You can see this in action in this updated Fiddle link: https://jsfiddle.net/mxq629ng/1/

Answer №2

To properly position the image element:

Remember to include the event as an argument in your function

function userClicked(event) {
    var x = event.clientX;
    var y = event.clientY;
    document.getElementById("xCoord").innerHTML=x;
    document.getElementById("snowballAppear").style.display = '';
    // Ensure fixed positioning - Element is placed relative to the browser window
    document.getElementById("snowballAppear").style.position = "fixed";
    // Distance from top of the browser window in pixels
    document.getElementById("snowballAppear").style.top  = y + "px";
    // Distance from left of the browser window in pixels
    document.getElementById("snowballAppear").style.left = x + "px";
}

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 dynamically add elements in AngularJS without relying on directives?

As a newcomer to Angularjs and not very fluent in English, I embarked on the journey of adding <li> using directives. You can see the result of my first attempt at this link. Next on my list was mastering two-way binding by passing values between th ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

Data is not appearing when using Node.js with mongoose and the populate() method

I am facing an issue while trying to display data from a database. Even though I have integrated 3 different schemas into one, the combined data is not being displayed as expected. I have attached all three schemas for reference. While async-await along w ...

Transformation of an Ajax array into an associative array

Currently, I am working on creating an API using Ruby on Rails and facing a challenge with sending an array through ajax. The task seems straightforward, but the issue arises when the array is received as an associative array instead of a regular one! Es ...

Initiate a click action upon receiving a focus event

I can't seem to figure out why this code is not functioning as expected: $('a').focus( function() { $(this).click(); }); Context: I am working on developing a form where navigating through different elements (such as textboxes) will au ...

Ways to ensure that the form data stays consistent and visible to the user continuously

Is there a way to ensure that the user submits the form, stores it in a MYSQL database, and then displays the same submitted data in the form field? <div class="form-group"> <label class="control-label col-sm-2" for="lname">Last Name*</l ...

There were no visible outputs displayed within the table's tbody section

import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = [{"id":1,"isActive":true,"object":"Communication","previ ...

Steps for updating a property of an object using a function

I am working on a function that resets the deepest value of an object with variable depth to 0. I need this function to update the object's property outside of its scope. var data = { '1': { '10000': { ...

What is the best way to cancel a Promise if it hasn't been resolved yet

Let's consider a situation where I have implemented a search function to make an HTTP call. Each call made can have varying durations, and it is crucial for the system to cancel any previous HTTP requests and only await results from the latest call. ...

Guide on positioning components to the right side of the NavigationDrawer in Vuetify with VueRouter

Working on my VueJS project, I've implemented a system to display content based on the user login using Firebase and Vuex state management. When a user is logged in, the content is shown using the v-if directive. Currently, I have successfully placed ...

All you need to know about the properties of CSS ul

When I specify .a ul{} .a ul li{} as well as .b ul{} .b ul li{} will the properties of ul in .b be completely isolated from the properties of ul in .a? Or will they have some commonalities? I am looking to ensure that the styles for ul remain entirely ...

creating tabulations and charts across various while loops

My goal is to create Tabs using information from the first while loop, and then populate a table within each Tab using data from the second while loop. The data is fetched date-wise from my 'treatment' table to generate the Tabs. The line items ...

Menu/navigation bar designed with floating lines and an array of color options

I'm currently working on implementing this specific menu into my Wordpress site. My main concern is figuring out how to customize the hover effect for each navigation item. Currently, the float line changes to red (background-color:#800; height:2px;) ...

How can I convert a string into JSON format in Node.js?

Imagine this scenario: a HTTP REST API has just sent me a JSON in the form of a string. How can I transform it back into a structured JSON object? ...

JavaScript variable not refreshing its value after submitting an HTML form

In my HTML form, I have 8 textboxes enclosed in div tags with IDs ranging from fa1 to fa8. By default, two of the textboxes are visible while the remaining six are hidden. To toggle the visibility of these divs, I've implemented two buttons - addfa an ...

What is the best way to incorporate a YouTube video into my HTML webpage?

Looking to add some YouTube links to my webpage - I'm a complete newbie and clueless about formats and embedding. Can someone guide me on what to use and how to insert it into my HTML code? Appreciate any help! ...

What is the best way to connect the "areaName" with the <TextBox> attributes value="" and onChange=""?

After calling an API and mapping the array, I have successfully bound the data on <TableCell> {this.state.allArea.map((allArea, i) => ( <TableRow > <TableCell >{allArea.areaName}</TableCe ...

Extracting every other value from an array can be achieved by iterating through the

Hi, I'm looking to create a function that will log every other value from an array. For example, if we have: var myArray = [1,45,65,98,321,8578,'orange','onion']; I want the console.log output to be 45, 98, 8578, onion... Does ...

Ways to conceal components of an external widget on my site

I'm attempting to add a chat widget to my website and I'm looking to hide specific elements within the widget. The chat function is provided by Tidio, but I believe this applies to most widgets. My main goal is to conceal a button that minimize ...

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...