skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You don’t need mouseup event just use click event on the parent container then apply the stopPropagation here, That prevents event bubbling upwards the document element so eventually select2 won’t close on x icon click.

    Bubbling-and-capturing DOC

    I have tested in your fiddle.

    $('.dropdown-menu').click(e=>{
       e.stopPropagation();
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search