JavaScript function replicating its own code with each execution

After running my function in the desired way, where I open the context menu and then click the button, I notice an interesting behavior. The first time I run it, I see my desired result. However, every subsequent time I run it, the success message is displayed multiple times based on how many times it has been executed. It seems to be adding one more success message each time.

For those curious, this issue pertains to a Leaflet Maps project.

Additionally, it's crucial for me to have the functions within the main map.on function in order to capture the coordinates of the click event.

map.on('contextmenu', function(e) {
    document.getElementById('context-menu').style.display = 'block';
    document.getElementById('context-menu').style.left = e.originalEvent.x + 'px';
    document.getElementById('context-menu').style.top = e.originalEvent.y + 'px';

    function copyCoordinates() {
        var lat = e.latlng.lat;
        var lng = e.latlng.lng;
        var zoom = map.getZoom();
        var params = 'lat=' + lat + '&lon=' + lng + '&zoom=' + zoom;
        var newUrl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?' + params;
        navigator.clipboard.writeText(newUrl);
        toastr.success('Copied coordinates to clipboard!', {timeOut: 5000})
        document.getElementById('context-menu').style.display = 'none';
        
    }
    document.getElementById('copyCoordinates').addEventListener('click', copyCoordinates);

    function copyCoordinatesFormatted() {
        var lat = Math.floor(e.latlng.lat);
        var lng = Math.floor(e.latlng.lng);
        var formatted = '"lat": ' + lat + ',\n  "lng": ' + lng + ',';
        navigator.clipboard.writeText(formatted);
        toastr.success('Copied coordinates to clipboard!', {timeOut: 5000})
        var flag = true;
        document.getElementById('context-menu').style.display = 'none';
    }
    document.getElementById('copyMarker').addEventListener('click', copyCoordinatesFormatted);
});

I attempted to address this by incorporating flags, but unfortunately, that did not resolve the issue.

Answer №1

Instead of EventListeners, I was able to solve the issue by using onclick.

    document.getElementById('copyCoordinates').onclick = copyCoordinates;

Grateful for the assistance!

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

Having trouble getting the dropdown to display JSON data properly

I am attempting to retrieve JSON data from a PHP file and utilize it to populate a dropdown menu. The JSON is being retrieved successfully from the PHP file and it appears as follows: [{"state":"AL"},{"state":"AK"},{"state":"AZ"},{"state":"AR"}] While i ...

The callbacks for the SignalR JavaScript Client are failing to trigger

Despite successfully connecting to my Hub and setting up the OnConnected and OnDisconnected functions to update an integer value and trigger a client callback with the new value, I am facing an issue in my angular application where the registered callback ...

Where does the 'Execution Context Destroyed' error originate from in my code?

Currently, I am developing a program to extract forum responses for the online University where I am employed. While I have managed to successfully navigate to the relevant pages, I encountered an issue when trying to include scraping for the list of learn ...

Using AngularJS to filter data on ng-repeat while also concealing the column header

I received an extensive JSON response from a REST service with information on numerous cities worldwide. The data structure is as follows (this is just a sample - typically it includes 100-200 places retrieved from the service and stored in the $scope item ...

Improve the parallax effect in your React component

Do you have any tips on smoothing out the scrolling animation for a React component with a simple parallax effect? I tried using requestAnimationFrame() in vanilla JS, but it doesn't seem to work well within the React component's rendering cycle. ...

Revise Bootstrap accordion setup

I currently have a Bootstrap accordion set up on my website using Bootstrap 4.1.0 <div id="accordion" class="mt-3"> <div class="card"> <div class="card-header bg-dark text-white" id="headingOne"> <h5 class="mb-0 f ...

React-Redux-Saga: Only plain objects are allowed for actions. Consider using custom middleware for handling asynchronous actions

Struggling to integrate redux-saga into my react app, I keep encountering this error: Actions must be plain objects. Use custom middleware for async actions. The error appears at: 15 | changeText = event => { > 16 | this.props.chan ...

Can Regex expressions be utilized within the nodeJS aws sdk?

Running this AWS CLI command allows me to retrieve the correct images created within the past 45 days. aws ec2 describe-images --region us-east-1 --owners self -- query'Images[CreationDate<`2021-12-18`] | sort_by(@, &CreationDate)[].Name&apos ...

Challenge facing React Native developers when importing image module

Currently delving into the world of React-Native and encountering a challenge when trying to import a static image. Here's a snippet of the code I have put together so far: 'use strict'; var React = require('react-native'); var { ...

Substitute a piece of text within an element while also preserving the formatting of a new line

My goal is to modify the text within the div tag "a/b" to "b/c" while preserving the line break that I have inserted in the HTML using the break tag. Currently, the text is being replaced, but I need the second line to appear below the first line. $(".t ...

Display Default Image in Vue.js/Nuxt.js when Image Not Found

I'm currently working on implementing a default image (placeholder image) for situations where the desired image resource is not found (404 error). I have a dictionary called article which contains a value under the key author_image. Although the stri ...

IE8 encountering issues with Jquery ajax() request

My current issue involves submitting data using ajax from forms with a class of ajax. This functionality works flawlessly in Firefox, Safari, and Chrome, but is unsuccessful in Internet Explorer. ajax: function() { $('form.ajax').live(&apo ...

Is the drag-and-drop feature not working properly?

I'm new to coding in Javascript and I'm attempting to insert an image inside a border created with CSS. Unfortunately, the script doesn't seem to be working properly. It's possible that there is a small error in the code causing the iss ...

The integration of cypress-cucumber-preprocessor with multiple testing frameworks appears to be experiencing compatibility issues

I am trying to set up a connection between Cypress and Cucumber, and I came across this plugin: https://www.npmjs.com/package/cypress-cucumber-preprocessor However, I am having trouble with my implementation as it seems to be missing. I have also added th ...

Steps for implementing a click event for a navigation drop-down using an HTML helper class

In my MVC 5 application, I have implemented a navigation dropdown. Here is the code snippet: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="menu> Report ...

Activating a function by pressing the enter key

I am currently developing code for a basic web application that calculates your words per minute as you type. The setup involves a table with a button that needs to be clicked once you finish typing. However, this process consumes some time and affects the ...

The sluggish performance of my website is being caused by the livereload process that was inserted into my index.hml file, causing it

Recently, I've noticed that this line of code is being inserted dynamically into my index.html file, either through Grunt tasks or directly from the server in Heroku. <script type="text/javascript">document.write('<script src="' + ...

Guide on connecting state from a higher-level component to a reusable selectInput component in Vue 3

I have a component named ChooseColor.vue that requires an array of color options for the selection input. The parent component where this ChooseColor component is included holds the user's information, specifically the favorite color property. How can ...

In TypeScript, the function is failing to retrieve the complete array value

I'm facing an issue with a program that is supposed to piece together all the letters, but it's not functioning correctly. I've tried using the debugger, but it doesn't display any errors. Here's the code snippet: var phrase = [ &a ...

Automating the movement of a slider input gradually throughout a specified duration

I am working on a website that includes a range input setup like this: <input type="range" min="1036000000000" max="1510462800000" value="0" class="slider" id ="slider"/> Additionally, I have integrated some D3 code for visualizations. You can view ...