Iordanis Iordanis - 26 days ago 17
jQuery Question

OpenLayers 3 - Div on top of map is not capturing click

I have a form/div displayed on top of the map. I want to make it so that it is hidden when there is a click outside the form/div area but not when the click is inside the form/div.

I can't get to detect when the click is done inside the div. Instead all clicks inside the form/div are detected as done on the map, as if the div doesn't exist.

<div id="map" class="map"><div id="popup">
//input data of form
</div> </div>


<script>
map.on('click', function(evt) {
console.log('Clicked #map');
//one method I tried from another stack overflow answer
(evt.target !== this) ? $("#popup").show() : $popup.hide();

var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature) {
return feature;
});

if (feature) {
loadInfo(feature.get('id'));
$("#popup").show();
}
});

$("popup").on('click', function(e) {
e.stopPropagation();
console.log('Clicked #popup');
});
</script>


Output


Clicked #map

Clicked #popup


As you can see in the code I tried few different methods on detecting clicks on the popup but none of them worked. All of them are as if, the popup is not even there.

I am using openlayers3 if that matters.

Answer

You can use Event.stopPropagation() to prevent further propagation of the current click event in the capturing and bubbling phases:

var $map = $('#map'),
    $popup = $('#popup');

$map.on('click', function(e) {
  console.log('Clicked #map');
  (e.target !== this) ? $popup.show() : $popup.hide();
});

$popup.on('click', function(e) {
  e.stopPropagation();
  console.log('Clicked #popup');
});
#map {
  background-color: grey;
  width: 80%;
  height: 120px;
  margin: auto;
  padding: 40px;
}

#popup {
  background-color:  #000000;
  color: #ffffff;
  width: 60%;
  margin: auto;
  padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="map"  class="map">
  <div id="popup">
    // input data of form
  </div>
</div>

Comments