Prevent click-through on overlaying divs in Leaflet maps

Is there a way to prevent an overlaying div on a leaflet map from being clickthrough? I tried setting pointer-events: none and auto on the overlaying div, but it didn't work. Setting pointer-events to none resulted in the radiobutton not being clickable anymore...

// Adding a tile layer to the map
var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
  osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  osm = L.tileLayer(osmUrl, {
    maxZoom: 18,
    attribution: osmAttrib
  });

// Initializing the map
var map = L.map('map').setView([19.04469, 72.9258], 12).addLayer(osm);

// Function for adding marker on map click
function onMapClick(e) {

  var marker = L.marker(e.latlng, {
      draggable: true,
      title: "Resource location",
      alt: "Resource Location",
      riseOnHover: true
    }).addTo(map)
    .bindPopup(e.latlng.toString()).openPopup();

  // Update marker position on drag end
  marker.on("dragend", function(ev) {

    var changedPos = ev.target.getLatLng();
    this.bindPopup(changedPos.toString()).openPopup();

  });
}

map.on('click', onMapClick);
#map {
    height: 500px;
    width: 80%;
    z-index: 1;
    position: relative;
}

.overlay {
  height: 500px;
  width: 100px;
  position: absolute;
  right: 0px;
  z-index: 2;
  background-color: rgba(255, 50, 50, 0.5);
  pointer-events: auto;
}
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<link href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" rel="stylesheet" />

<div id="map">
  <div class = "overlay">
    <input type="radio" class = "someButton">Foo Bar
    </div>
</div>

Answer №1

An alternative approach is to utilize a function offered by the leaflet library itself.

var container = L.DomUtil.get('overlay'); // note that this should be an element ID, not a class!
L.DomEvent.on(container, 'mousewheel', L.DomEvent.stopPropagation);
L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);

Answer №2

One possible solution is to relocate your overlay div from inside the map and position it above by using negative margins and adjusting the z-index. Here's an example:

// To enhance the map functionality, we can add a tile layer such as OSM tile layer.
// Setting up the URL template for the tile images is typically part of creating a tile layer
var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
  osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  osm = L.tileLayer(osmUrl, {
    maxZoom: 18,
    attribution: osmAttrib
  });

// Set the initial view of the map using a specific center point and zoom level
var map = L.map('map').setView([19.04469, 72.9258], 12).addLayer(osm);

// Include the script to add a marker on map click event
function onMapClick(e) {

  var marker = L.marker(e.latlng, {
      draggable: true,
      title: "Resource location",
      alt: "Resource Location",
      riseOnHover: true
    }).addTo(map)
    .bindPopup(e.latlng.toString()).openPopup();

  // Update marker position upon dragging
  marker.on("dragend", function(ev) {

    var changedPos = ev.target.getLatLng();
    this.bindPopup(changedPos.toString()).openPopup();

  });
}

map.on('click', onMapClick);
#map {
    height: 500px;
    width: 100%;
    float: left;
    z-index: 1;
    position: relative;
}

.overlay {
  height: 500px;
  width: 100px;
  margin-left: -100px;
  position: relative;
  float: right;
  z-index: 2;
  background-color: rgba(255, 50, 50, 0.5);
  pointer-events: auto;
}
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<link href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" rel="stylesheet" />

<div id="map">
</div>

<div class="overlay">
    <input type="radio" class = "someButton">Foo Bar
 </div>

Answer №3

Relocate the overlay div outside of the map element:

// We will insert a tile layer to enhance our map, using an OSM tile layer.
// Setting the URL template for the tile images is essential when creating a tile layer
var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
  osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  osm = L.tileLayer(osmUrl, {
    maxZoom: 18,
    attribution: osmAttrib
  });

// initializing the map on the "map" div with a specified center and zoom level
var map = L.map('map').setView([19.04469, 72.9258], 12).addLayer(osm);

// Function for adding a marker on map click
function onMapClick(e) {

  var marker = L.marker(e.latlng, {
      draggable: true,
      title: "Resource location",
      alt: "Resource Location",
      riseOnHover: true
    }).addTo(map)
    .bindPopup(e.latlng.toString()).openPopup();

  // Update marker position upon dragging
  marker.on("dragend", function(ev) {

    var changedPos = ev.target.getLatLng();
    this.bindPopup(changedPos.toString()).openPopup();

  });
}

map.on('click', onMapClick);
.container {
    position: relative;
    width: 500px;
}
#map {
    height: 500px;       
}

.overlay {     
  width: 100px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;      
  background-color: rgba(255, 50, 50, 0.5);     
}
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<link href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" rel="stylesheet" />

<div class="container">
    <div id="map"></div>
    <div class = "overlay">
        <input type="radio" class = "someButton">Foo Bar
    </div>
</div>

Answer №4

To prevent the click event from propagating to lower layers while maintaining pointer-events: auto;, you can try the following:

<div class = "overlay" onclick="alert(event);event.stopPropagation();">

In this example, I have used event.stopPropagation(); inline, but you could also use a function in your JavaScript.

// Adding a tile layer to the map using Leaflet.js
var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
  osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  osm = L.tileLayer(osmUrl, {
    maxZoom: 18,
    attribution: osmAttrib
  });

// Initializing the map with a center and zoom level
var map = L.map('map').setView([19.04469, 72.9258], 12).addLayer(osm);

// Function for adding a marker on map click
function onMapClick(e) {

  var marker = L.marker(e.latlng, {
      draggable: true,
      title: "Resource location",
      alt: "Resource Location",
      riseOnHover: true
    }).addTo(map)
    .bindPopup(e.latlng.toString()).openPopup();

  // Update marker position when dragged
  marker.on("dragend", function(ev) {

    var changedPos = ev.target.getLatLng();
    this.bindPopup(changedPos.toString()).openPopup();

  });
}

map.on('click', onMapClick);
#map {
  height: 500px;
  width: 80%;
  z-index: 1;
  position: relative;
}

.overlay {
  height: 500px;
  width: 100px;
  position: absolute;
  right: 0px;
  z-index: 2;
  background-color: rgba(255, 50, 50, 0.5);
  pointer-events: auto;
}
<script src="https://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<link href="https://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" rel="stylesheet" />

<div id="map">
  <div class="overlay" onclick='console.log("Event: "+ event.type);event.stopPropagation();'>
    <input type="radio" class="someButton">Foo Bar
  </div>
</div>

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 pop-up notification for a compact disc

Received a CD containing various tutorials created in HTML. I am looking to have a browser window open with specific parameters, such as no toolbars and fixed width/height, to properly display the content. Using window.open with multiple parameters trigge ...

Limiting the scope of elements in HTML and JavaScript through the use of namespaces

Recently, I've been noticing a trend where Developer A creates a new feature, such as an autocomplete input, without using any frameworks, combining HTML and JavaScript in the same file. The code for the feature might look something like this: <!- ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

Having issues with the JavaScript voting system {{bindings}} returning null when clicked?

It seems like the error is not appearing in the developer tool, so it might be related to how the data is being read. Both {{upVote}} and {{downVote}} start with no value and show null when clicked, indicating that the buttons are somehow linked. I was att ...

Retrieve the background color using code-behind

Despite its humorous appearance, I am having trouble with the Syntax :( I have a background color in my code behind file and need to correct the syntax here so that my Table displays the correct background color: <Table style="background-color:" &apos ...

Bootstrap 4 - positioning link element to align with heading in card header

I'm currently utilizing Bootstrap 4+ to design a card that features a collapsible card-body, triggered by a link located in the card-header. <div class="card text-left mb-3 mt-3"> <div class="card-header p-3"> <h4>Where should ...

Place the dataLabel above a specified column in Highcharts

My bar chart has a stacked design, with an invisible bar added to the height of the tallest bar to ensure clickability even for small values. Without this invisible stack, columns with a value of 1 would be difficult to click on. One issue I am facing is ...

Steps for adding an array of JSON objects into a single JSON object

I have a JSON array that looks like this: var finalResponse2 = [ {Transaction Amount: {type: "number"}}, {UTR number: {type: "string"}} ] My goal is to convert it into the following format: responses : [ { Transaction Amount: {type: "number"}, UTR numbe ...

Avoiding multiple ajax requests due to multiple clicks

I have a blog on WordPress that has a jQuery code allowing users to click a bookmark link to save the post as a bookmark. Each post displays a total bookmark counter in this format: "Bookmarked (5)". The issue is that when a user clicks multiple times on t ...

PHP code failing to save form information into database

I am experiencing difficulties with inserting form data into my database. The connection to the database is successfully established without any errors, but no information is being entered. Below is my code - any assistance would be greatly appreciated. ...

Disable the ability for new windows, such as popups, submit buttons, and forms with the target set to blank, to reference

Encountering an issue, I stumbled upon some solutions here and on various other websites that I would like to share with you. The Problem: The window.opener functions of child pages stopped working after some security updates in modern browsers around 202 ...

Encountering a TypeError stating that searchField.toLowerCase is not a function while employing hooks and redux in the

I've been working on a project to dive deeper into react. Recently, I made the switch to using hooks and attempted to integrate redux into it. However, I encountered an error that says: TypeError: searchField.toLowerCase is not a function After consu ...

"Step-by-step guide on deactivating SmartyStreets/LiveAddress with an onclick function

I've recently taken over a SquirrelCart shopping cart application that utilizes SmartyStreets/LiveAddress code, and I'm struggling to figure out how to disable the verification process when copying billing address fields to shipping address field ...

Gaining entry into a JSON object

I'm currently working on a web page that utilizes API data from the Breaking Bad website. I have received this data in JSON format, but I am struggling to figure out how to access only the objects where the "author" is "Walter White." Here is the data ...

Node.js routing issues leading to rendering failures

I have been working on a website that involves carpooling with drivers and passengers. When a driver submits their details, they are directed to a URL where they can select the passenger they want to ride with. Here is the code snippet I have written: ap ...

After implementing the ng-repeat directive, the div element vanishes

I've been working on fetching data from a Json API and displaying it on user event. However, I'm facing an issue where the div disappears whenever I apply the ng-repeat property to it. Despite searching through various tutorials and documentation ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

using node.js to extract a cookie from a 302 redirect

Need help simulating a login using node.js. The request is a post method and returns a 302 status code. However, when trying to simulate the request in node, I encounter the following error: Error handling unrejected promise: StatusCodeError: 302 Upon i ...

Angular binding causing decimal inaccuracies

Within my $scope, I have a variable tobing that can be either 2.00 or 2.20, and I am binding it to: <span>{{datasource.tobind}}</span> I want the displayed text to always show "2.00" or "2.20" with the two last digits, but Angular seems to au ...

Using jquery to submit a form with multiple fields spread across various tabs

Utilizing a bootstrap modal, I aim to display detailed information about a single product. Within this modal, there are three tabs categorized as details, image, and specification for the respective content components of the product. Upon clicking the edi ...