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 style="left:' calc_x 'px ;top:' calc_y 'px"></div>');
}
$('body').on('click', '.cp_select', function(event) {
event.stopImmediatePropagation()
$(this).remove()
return false;
});
CodePudding user response:
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 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;
}
CodePudding user response:
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 ></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 ></div>