interaction with leaflet popup information

My aim is to access the content within a leaflet popup. Specifically, I have inserted a form with buttons inside it that I would like to interact with. However, for now, I am simply attempting to add an event to the popup itself.

$(".leaflet-popup-content-wrapper .leaflet-popup-content").click(function(e) {
  alert("clicked");
});

Check out an example of a marker with a popup using LeafletJs:

<form class="popup-form">
  <div class="form-group">
    <label class="mb-0" for="comment">Comment:</label>
    <textarea class="form-control" rows="4" class="comment">${feature.properties.note}</textarea>
  </div>
  <div class="d-flex">
    <button type="submit" class="btn btn-outline-info btn-sm">Save</button>
    <button class="delete-button btn btn-outline-danger btn-sm ml-auto">Delete</button>
  </div>
</form>

Here is the code where the popup content is defined:

var points = new L.geoJson(null, {

  onEachFeature: function (feature, layer) {
    layer.bindPopup(feature.properties.note);

    let myPopup = L.DomUtil.create('div', 'content');

    content = `
    <form class="popup-form">  
      <div class="form-group">
        <label class="mb-0" for="comment">Comment:</label>
        <textarea class="form-control" rows="4" class="comment">${feature.properties.id}</textarea>
      </div>
      <div class="d-flex">  
        <button type="submit" class="btn btn-outline-info btn-sm">Save</button>
        <button class="delete-button btn btn-outline-danger btn-sm ml-auto">Delete</button>
      </div>
    </form>
    `;

    layer.bindPopup(content);

    $('#form', myPopup).on('click', function() {
      alert("form clicked")
  });

I came across this post on how to catch the click event on a leaflet popup, which inspired me.

I am puzzled by the 'context' in the code example below:

var content = L.DomUtil.create('div', 'content'),
    popup = L.popup().setContent(content);

L.DomEvent.addListener(content, 'click', function(event){
    // do stuff
}, context);

Answer №1

In order to access the delete button class, one approach is to utilize the on("popupopen") event on layer.bindPopup(popupContent).

This method eliminates the necessity of employing leaflet's L.DomUtil. By listening to the popupopen event, you can also listen to jquery's click event using the delete button's class to trigger the delete event from the delete button. It is recommended to use preventDefault to prevent a page refresh.

function onEachFeature(feature, layer) {
  const popupContent = `
    <form class="popup-form">  
      <div class="form-group">
        <label class="mb-0" for="comment">Comment:</label>
        <textarea class="form-control" rows="4" class="comment">${
          feature.properties.id
        }</textarea>
      </div>
      <div class="d-flex">  
        <button class="btn btn-outline-info btn-sm">Save</button>
        <button class="delete-button btn btn-outline-danger btn-sm ml-auto">
           Delete
        </button>
      </div>
    </form>
    `;

  if (feature.properties && feature.properties.popupContent) {
    popupContent += feature.properties.popupContent;
  }

  layer.bindPopup(popupContent).on("popupopen", () => {
    $(".delete-button").on("click", e => {
      e.preventDefault();
      alert(`now delete layer with id ${feature.properties.id}`);
    });
  });
}

Check out the Demo here

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

Show a notification if the ajax response is empty

After creating a simple table with ajax response, I noticed that the values for approvedOn and approvedBy are coming up as null. https://i.stack.imgur.com/FkJTL.png However, I would prefer to display them as pending instead of null. Any suggestions on h ...

Content on the page is not fully visible on mobile devices when the Right-to-Left attribute is applied

I recently added multilanguage support to my blog using the RTL attribute. However, I noticed that when users switch to another language, the page content shifts from LTR to RTL. Everything was working fine until I encountered an issue with a toggle tab o ...

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

What is the best way to access attributes from a div element?

I am currently working on extracting attributes from within a div tag, specifically the custom attributes of the first child element. I am using web scraping techniques with Node.js and Puppeteer. My goal is to retrieve the custom attributes data-ticker, d ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

The many potentials of looping through Sass maps

My sass map contains a variety of color shades, and the full code can be found on Codepen: $pbcolors: ( pbcyan : ( 50: #E5F5FC, 100: #CCEBF9, 200: #99D7F2, 300: #66C3EC, 400: #33AFE5, 500: #009DBF, 600: #008CAB, 700: #007C98, 800: #006D85, 900: #005D72 ...

Implementing RequireJS Singleton pattern with Web Workers

I'm currently working on a JavaScript project that utilizes the latest version of RequireJS. One of the modules I am defining is chessWorker, as shown below: var worker; define("chessWorker", ["jquery", "messageListener"], function($, listener) { ...

What is the best way to send multiple variables to a url using jQuery ajax?

I am having trouble passing multiple values in the method below. Can someone help me with the correct syntax? I have attempted data: ('keyword='+$(this).val(),'id='10), as well as data: {'keyword='+$(this).val(),'id=&a ...

Use Backbone.js to dynamically insert partial views based on specific routes, similar to how ng-view works in AngularJS

After gaining experience with AngularJs, I am now looking to dive into Backbone.js. However, I am struggling to understand how this library handles routes and partial views/templates "injection". In Angular, we can easily set up static components like th ...

Is there a way to determine if a line has been automatically wrapped within a textarea element?

Is it possible to detect when text is wrapped onto the next line in a textarea after becoming wider than the area? ...

My browser isn't triggering the jQuery change event, although it does work in jsfiddle

Whenever a textbox is changed, I want a specific function to be executed automatically. The code snippet below demonstrates my approach: var div = document.getElementById("tree"); var input = document.createElement('input'); input.id = 123; i ...

The text becomes jumbled and messy when the browser is resized

I came across this fantastic header design > https://codepen.io/rm/pen/ldhon <. However, I noticed that when the window is resized, the text ends up overlapping. In the demo provided, resizing the window too much causes the issue to become apparent, ...

The positioning and floating of two divs are set to fixed without using percentage width, however, the functionality is not

Apologies for my poor English writing :) I am attempting to float two divs side by side in a fixed position, without using percentages. This code works well on most browsers but is not compatible with IE 6. HTML <div class="right"></div> < ...

Creating a custom comparison method between two select dropdowns using the jQuery Validation plugin

In my HTML code, I have two select elements: <label for="h_slat_type">Horizontal Slat Type</label> <select name="h_slat_type" id="h_slat_type"> <option disabled="disabled" selected>Select</option> ...

What could be causing the HTML and CSS to not show the background image?

Hey, I'm new to html and css and I'm having trouble getting a background image to show up on my website. All I see is "first website" in the corner but the image isn't displaying. Here's the code I have: * { margin: 0; padding: 0 ...

Expanding the outer div with Jquery's append() function to accommodate the inner div elements perfectly

I am facing an issue where my outer div does not expand automatically to fit the elements I append inside it using jQuery. The structure of my div is as follows: <div class="well" id='expand'> <div class="container"> < ...

Expand and collapse divs using jQuery when a JavaScript do_PostBack link is clicked

Currently, I am in the process of developing a website called TheDigitalScale. One particular feature on the site involves using jQuery to create an expanding div that opens when clicked and closes with another click. <script type="text/javascript"> ...

How to reference a ListView control using its DataSource in a C# class

Currently, I have a ListView embedded in a webpage connected to a C# class datasource called CommentsDAO. This class contains the necessary methods to retrieve or delete data from the ListView. While data retrieval is successful, deleting a row proves to b ...

Javascript onclick events failing to toggle video play/pause functionality

In my website, I have background music and a background video (webm format) embedded. I am facing an issue with making play/pause buttons in the form of png images work for both the video and the music. The background music is added using the embed tag wi ...

A guide to examining the HTTP response body, including HTML content, using Wireshark

After entering the URL in the address bar of the virtual machine's browser, a request for an HTML document from my host computer was made. The HTML document, which I had personally written, successfully appeared in the virtual machine's browser. ...