JavaScript | Determining the coordinates of where on the image X and Y were clicked

My goal is to determine the position of an x and y location when a user clicks on an image. This information will be used to add a spot to the image that displays relevant information. The content for the spot will be dynamically loaded from a SQL database, but my current focus is on getting the positioning right.

I've searched on Stack Overflow and found suggestions to use e.pageX - element.offsetLeft for the x location and e.pageY - element.offsetTop for the y location. However, when I tried placing a div with coordinates like

<div style="position: absolute; top: 253px; left: 50px;"></div>
, it didn't appear where I expected it to be. The left coordinate represents the x position and the top coordinate represents the y position.

To summarize, here's what I'm trying to accomplish:

  • A lightbox should appear in the middle of the screen with the selected image displayed.
  • When users click on the image, the x and y coordinates are calculated and then used to position an element using CSS exactly where they clicked on the image.

var $imgCont = $('#img-wrap'),
    $img = $('#img')

$img.click(function(e) {
  var pos = {
    left: e.pageX - $img.offset().left,
    top: e.pageY - $img.offset().top
  }
  $('<div class="box">').css(pos).appendTo($imgCont)

})
#img-wrap {
  position: absolute;
  background-color: rgba(0,0,0,.7);
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 16px;
  height: 16px;
  position: absolute;
  background: red;
  z-index: 100
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click image to add boxes</p>
<div id="img-wrap">
  <img id='img' src=http://via.placeholder.com/400x400 ">
</div>

Answer №1

Ensure that the image is enclosed within a container with a specified position, and then add it to the same container

var $imgCont = $('#img-wrap'),
    $img = $('#img')

$img.click(function(e) {
  var pos = {
    left: e.pageX - $img.offset().left,
    top: e.pageY - $img.offset().top
  }
  $('<div class="box">').css(pos).appendTo($imgCont)

})
#img-wrap {
  position: relative;
  margin: 60px 0 0 60px;
  border: 1px solid green;
  padding: 2px;
  width: 400px
}

.box {
  width: 16px;
  height: 16px;
  position: absolute;
  background: red;
  z-index: 100
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click image to add boxes</p>
<div id="img-wrap">
  <img id='img' src=http://via.placeholder.com/400x400 ">
</div>

Answer №2

One option is to utilize the offsetY and offsetX properties from the click event parameter

<div>
  <p>
    Display your image here
  </p>
  <div id='container' style="position:relative">
    <img id="myImage" src="http://lorempixel.com/200/120/" />
  </div>

$(document).ready(function() {
  $(myImage).click(
    function(e) {

      var $newContainer = $("<div>You have clicked this area</div>");

      $newContainer.css({
        position: 'absolute',
        top: e.offsetY,
        left: e.offsetX,
        height: '20px',
        'background-color': "red"
      });

      $(container).append($newContainer)
    }
  );
});

For a live example, check out this fiddle

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 load a Twitter widget from dynamically loaded HTML using AJAX?

I've been attempting to implement a standard Twitter search widget directly from the Twitter website: <script src="http://widgets.twimg.com/j/2/widget.js"></script> <script> new TWTR.Widget({ version: 2, type: 'search' ...

ng-include: Child scope access problem

I am currently facing an issue with my app while using DayPilot Scheduler. home.html: <div class="container-fluid"> <daypilot-scheduler id="scheduler" daypilot-config="schedulerConfig" daypilot-events="events"></daypilot-scheduler> ...

Issue with jQuery Ajax file upload in CodeIgniter

I am attempting to use AJAX to upload a file in the CodeIgniter framework, but I encountered an error message stating 'You did not select a file to upload.' Please review this code: View <form method="POST" action="" enctype="multipart/form- ...

Is there a way to enforce mandatory fields on material-table?

During my current project, I am utilizing a material-table interface to perform CRUD operations. I am interested in finding out if there is a way to make certain fields required when necessary. Despite my research efforts yielding minimal results, I have ...

Is there a way to open a link in a new window without using the _blank attribute?

I am facing an issue where I have a webpage with a URL linking to a PHP file that displays an image, and I want to open this picture in a new window without the blank page showing up. Currently, when I click on the URL using the code below, a new window o ...

The property length is undefined and cannot be read

I'm currently utilizing a dexi.io robot for the purpose of automating data extraction from permit databases. This particular robot has the capability to process custom JavaScript in order to dissect the incoming JSON object. While this code does func ...

The method to extract the followers of an Instagram account using node.js, cheerio, and InstAuto/Puppeteer

Currently, I am attempting to develop a program that generates lists of users who follow specific profiles, and vice versa. Since the Instagram graph API is now inactive, this task has become quite challenging. Despite identifying the correct div element, ...

How can I use JQuery ajax to dynamically update an HTML element without continuously polling for updates every few seconds?

Is it possible to monitor database updates without relying on setInterval? My issue is that I need to update the video source within a video tag, but continuously checking for updates will cause the video to refresh unnecessarily. I want the video to onl ...

Phone Validation for Contact Form 7

Recently, I was tasked with creating a landing page for a job interview. The challenge was to include validation on the phone number field so that it has to be between 9 and 10 numbers in length, along with another validation requiring the phone number t ...

Is it possible for an HTML file to not recognize an external CSS stylesheet?

I've been trying everything, but I can't seem to get these two documents to work together. I'm confident that the CSS file is linked correctly with the right file name. I decided to give it a shot after watching this coding blog tutorial on ...

Converting values into keys and vice versa in JavaScript: A comprehensive guide

I have an array of Objects where I want to convert the first value into a key and the second value into a value. Please review the question below along with my desired output: [ { "name": "Unknown", "value": "R ...

What is the best way to display a mongodb _id in HTML using AJAX?

Using an ajax function to fetch employees using the code provided below, I am attempting to incorporate the mongodb _id field into the checkbox id attribute. However, after rendering in the browser, the output appears as follows: <input id="[object Obj ...

What is the process for invoking an External Javascript Firestore function within a Typescript file?

Trying to figure out how to integrate a Firestore trigger written in an external JavaScript file (notifyNewMessage.js) into my TypeScript file (index.ts) using Node.js for Cloud functions. Both files are located in the same directory: https://i.stack.imgu ...

Error Message: "BlurbError on /taskapp/taskapp-board/ Failed to parse the remaining: '(status='fresh')' from 'tasks.filter(status='fresh')'"

I encountered an error known as "TemplateSyntaxError." I have created a project that manages tasks, and within this app, I developed a task-board.html page to handle user tasks. This page consists of three sections: 1) Add New Task, 2) In-progress Tasks, a ...

Attempting to insert a line break tag within the text using React

Having trouble inserting line breaks in text using React. Can anyone guide me on how to achieve this? I've attempted adding the br tag, but it is displaying as in the browser. Here's a snippet of my code. Appreciate any help or advice. let sp ...

In search of a fresh and modern Facebook node template

I've been on the hunt across the internet for a quality node.js Facebook template, but all I seem to stumble upon is this https://github.com/heroku/facebook-template-nodejs. It's okay, but it's built using express 2.4.6 and node 0.6.x. I wan ...

JavaScript conditional calculation mechanism

Here is the code snippet I am referring to: function myFunction() { var x = document.getElementById("ins-feet").value; if(x >= 0 && x <= 1499) { document.getElementById("show-cost").innerHTML = "Cost: $" + 300; } else if ...

Assign a distinct color to each character of the Russian alphabet within a specified text using CSS and/or JavaScript

My experiment involves testing the concept of "induced synesthesia" by assigning different colors to individual characters in text. I plan to map each character in the Russian alphabet to a specific color, for example, A is red, B is blue, and so on, resul ...

Accordion borders in Bootstrap do not appear at the top when accordion items are hidden

I am currently using a Bootstrap 5 accordion component on my website. Additionally, I have implemented a JavaScript code snippet that allows users to search and hide specific accordion items dynamically. However, I have noticed that when the top accordion ...

How can I utilize JavaScript to seamlessly loop through and display these three images in succession?

My current code is HTML, CSS, and JS-based. I am looking to design three of these div elements that appear and hide in a loop every 3-5 seconds. After the first run, I want the execution to repeat continuously. How can I modify my code to achieve this func ...