I want to prevent click propagation on the following element:
.select2-selection__choice__remove
I try this:
$(document).ready(function () {
$("document").on(
"mouseup",
".select2-selection__choice__remove",
function (event) {
event.stopPropagation();
event.preventDefault();
},
);
});
The example I want to solve is this:
https://jsfiddle.net/dk_dragonknight/c1ef7138/
I need that, when clicking on the "x" icon on the left side of the tag, the dropdown does not close (stopPropagation needs to work for this).
Note: this is just a code I posted to reproduce the problem, it’s not mine and therefore I need a solution for this here
2
Answers
If you want to stop events propagating from an element that you need to bind your event listener to that element.
You are currently using event delegation. You’ve bound the event listener to the document and are testing to see if it propagated from the select to the document before calling your function.
By the time you call stopPropagation, the event has propagated almost as far as it was going to anyway.
You don’t need
mouseup
event just useclick
event on the parent container then apply thestopPropagation
here, That prevents event bubbling upwards thedocument
element so eventually select2 won’t close onx
icon click.Bubbling-and-capturing DOC
I have tested in your fiddle.