'jQuery stopPropagation not stopping click through
I have a panzoom plugin that is working well. When I click on var elem it adds a small div cp_select in the correct location. Then, when I click on that newly created cp_select div, it removes that div. So you can add and remove it accordingly. However, when I click on the cp_select div, it removes it then immediately adds it back in because the click is propagating through. I have tried event.stopPropagation() and event.stopImmediatePropagation() with no luck. Any ideas how to prevent the cp_select firing the map_click(e)?
window.panzoom = panzoom(elem, {
onClick(e) {
map_click(e);
}
})
function map_click(e) {
$(".map_cont").prepend('<div class="cp_select" style="left:'+calc_x+'px ;top:'+calc_y+'px"></div>');
}
$('body').on('click', '.cp_select', function(event) {
event.stopImmediatePropagation()
$(this).remove()
return false;
});
Solution 1:[1]
The problem must be specifically with however panzoom is dealing with its onClick, or otherwise in code not shown in the question; if I substitute a plain click event handler on the window in place of your panzoom call, event.stopPropagation() works as expected.
// nonessential code removed and simplified for demo
function map_click() {
$(".map_cont").prepend('<div class="cp_select"></div>');
}
$('body').on('click', '.cp_select', function(event) {
$(this).remove();
event.stopPropagation();
});
window.onclick = map_click // stand-in for your panzoom function
.cp_select {
border: 3px solid;
height: 20px; width: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(click anywhere)
<div class="map_cont"></div>
Solution 2:[2]
Why not just toggle a visibility class of the clicked cp_select item?
// adjust values of below variables
let rowCount = 10;
let colCount = 10;
let tileSize = 50;
let mapCont = $(".map_cont"); // if this is a single item, consider using an id instead of a class
// start with adding hidden .cp_select items on all tiles
for (let i = 0; i < rowCount; i++) {
for (let j = 0; j < colCount; j++) {
let top = i * tileSize;
let left = j * tileSize;
let tile = `<div class="cp_select hide" style="top:${top}px ;left:${left}px"></div>`;
mapCont.prepend(tile);
}
}
$(document).on('click', '.cp_select', function(event) {
$(this).toggleClass("hide");
});
And add the below css rule
.hide {
display: none;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | burkay |

