Iordanis Iordanis - 1 year ago 94
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>

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

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

if (feature) {

$("popup").on('click', function(e) {
console.log('Clicked #popup');


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 Source

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');
  ( !== this) ? $ : $popup.hide();

$popup.on('click', function(e) {
  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=""></script>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download