Storing the clicked mouse coordinates in an array using JavaScript

I want to add the coordinates of a mouse click on a specific element to the end of an array. Below is my code snippet:

IN THE HEAD:

var seatsArray = [];

IN THE BODY:

var coordinates = document.getElementById("image");
coordinates.onclick = function(event) {
  seatsArray.push(offsetX, offsetY);
}
document.write("Seats array now includes: " + seatsArray + ".");

Seems like a simple issue, but I'm still new to javascript. Any guidance on why it's not functioning would be highly appreciated!

Thanks

Answer №1

Make a simple change to your click event like this:

coordinates.onclick = function(event) {
  event = event || window.event;
  if (!window.event) { // for Firefox
    event.offsetX = event.layerX;
        event.offsetY = event.layerY;
  } 
  seatsArray.push(event.offsetX, event.offsetY);
}

Firefox uses offsetX/Y as layerX/Y, while IE has a global event object.

If you want global coordinates, use this method:

coordinates.onclick = function(e) {
e = e || window.event;

if (e && e.pageX && e.pageY) {
            e.posX = e.pageX;
            e.posY = e.pageY;

        } else if (e && e.clientX && e.clientY) {
            var scr     = {x:0,y:0},
                object  = e.srcElement || e.target;
            //calculating scroll
            for (;object.parentNode;object = object.parentNode) {
                scr['x'] += object.scrollLeft;
                scr['y'] += object.scrollTop;
            } 
            e.posX = e.clientX + scr.x;
            e.posY = e.clientY + scr.y;
        } 
 seatsArray.push(e.posX, e.posY);
}

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

Attempting to send data as arguments in an axios request

I have been working on setting up a forum and I want to implement a feature where clicking on a post title will take the user to a page I've already created that displays the title and body of the post. I utilized MUI for building the page, but I enco ...

The JavaScript image slideshow functions perfectly when run from a local environment, however, it encounters

It seems like you all are my go-to team for JavaScript assistance. I've encountered an issue with a slideshow on my webpage. The slideshow works perfectly fine when I load the local copy of the page, but it fails to function properly when I load the a ...

Combining an array of intricate data models to create

Currently, my setup involves using Entity Framework 7 in conjunction with ASP.NET MVC 5. In my application, I have various forms that resemble the design showcased in this image. By clicking on the "new" button within these forms, a Bootstrap modal like t ...

Display the array values in Node.js on new linesorNode.js: Display array values

Here is an example of an array: var fruits = ['apple', 'banana', 'orange'] I need to show this array in a new format, with each value on its own line. How can I achieve this? New formatted display [ 'apple', &apo ...

The function executes without issue initially but then consistently encounters errors

I'm facing an issue with my function running only once as expected. The JSON data for GhStatus and CsStatus is 0, so I anticipate receiving two "crash" alerts. However, the alerts are only triggered once. In Chrome Developer tools, I receive errors e ...

Utilizing OpenLayers3 to create a global JavaScript variable

What could be the reason for this code working? function addMap() { var view = new ol.View({ center: ol.proj.fromLonLat([29.5646, 44.1575]), zoom: 4 }); var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Til ...

Error in Javascript: unable to locate the imported module

When attempting to import the 'CryptographyClient' module from a specified directory, I encountered an issue. Initially successful in typescript, but after compiling the code into javascript, an error was thrown stating that it could not find the ...

Creating a Customized Pop-up Box with Bootstrap CSS and JQuery/Java Integration

I have a filter box that appears when the filter icon is clicked, but it currently lacks Bootstrap styling. I am in the process of upgrading the website to Bootstrap3 HTML5. The current appearance of the filter icon is as follows: However, we want it to ...

What is the best way to initiate a saga for an API request while another call is currently in progress?

During the execution of the first action in saga, the second action is also being called. While I receive the response from the first action, I am not getting a response from the second one. this.props.actions.FetchRequest(payload1) this.props.actions.F ...

Troubleshooting: Issue with Nested jQuery UI Accordion Implementation

I am having issues with the menu collapsing incorrectly. While the top level functions properly, the sub menus do not collapse as expected. I am unsure about the correct approach to fix this problem. Can anyone provide guidance? jquery $(function() { ...

What is the best way to swap out the outdated schemas for the updated ones?

Hello there! I have some schemas set up like this: { user: '123', code: 'abc', uses: [...] }, { user: '123', code: 'def', uses: [...] }, and my goal is to transform them into this format: { user: '123', co ...

Regular expressions should be utilized in a way that they do not match exactly with a

Can someone help me create a regular expression for an html5 input pattern attribute that excludes specific items? How can I convert ab aba ba into a pattern that will match anything that is not exactly one of these words? For example, I want the fol ...

Utilizing Fragments in Vuejs 2.x with Jsx - A User's Guide

Considering the presence of Fragments in React and the lack of a specific solution in the official Vuejs GitHub thread, what alternative methods could be used in Vuejs? This information may be beneficial for developers transitioning from a React backgrou ...

Personalize the file button for uploading images

I have a button to upload image files and I want to customize it to allow for uploading more than one image file. What is the logic to achieve this? <input type="file" />, which renders a choose button with text that says `no files chosen` in the sa ...

Disabling the Annoying Video Popup Ad that's Blocking my "Load More" Feature in Selenium

I am currently in the process of scraping around 1000 URLs using Selenium, and I am very close to getting it to work smoothly. Each URL contains a "load more" button that I keep clicking until a Stale Element exception is thrown, which I handle. Everything ...

Exploring the Concept of Event Bubbling in ReactJS

Having recently delved into React.js, I've encountered a roadblock that has persisted for the past three days despite my attempts at various solutions. The issue revolves around two functions in my parent component named checkout: handleSeleteAddress ...

What is the best way to enable horizontal scrolling for textarea overflow in a smooth manner like input, without any sudden jumps?

Currently, I am interested in utilizing a one-line textarea (with rows=1 and overflow-x:hidden;) similar to input type="text. However, I have encountered an issue where the content scrolls with "jumps" while typing inside it: https://i.stack.imgur.com/Rzf ...

How can I rearrange divs using CSS? Can I add parent 1 in between the children of parent 2

Check out my current HTML code structure: <div class="container> <div class="parent1"></div> <div class="parent2"> <div class="child1"></div> <div class="child2"></div> </div ...

What is the best way to reset local state after triggering a success action in Redux Saga?

I'm looking to reset my component state after a successful call in redux saga. Is there a way to achieve this? Currently, I am using the component state to track my input value. this.state = { department: '', }; The solution I have im ...

Update the 'duplicate' buttons according to the position in the array

My app features 14 buttons, each generating a replica button with the same text when clicked. The pre-existing buttons are numbered to aid in iteration. I'm currently attempting to organize the newly created replica buttons in ascending order from lef ...