Search code examples
javascriptjqueryjquery-uijquery-ui-draggablejquery-ui-droppable

Click event not being bound when added in callback


I am dragging an li element, and dropping it to ul. I want to register click handler for this li element.

However, click event is not being fired.

            function initListClickEvent() {
                $("#list1 > li").click(function () {
                    $(this).css("background-color", "blue");
                    $(this).css("color", "white");
                });
            }

            $(document).ready(initListClickEvent);

            $(function () {
                $("#list1").droppable({
                    accept: 'li',
                    drop: function (e, ui) {
                        initListClickEvent();
                    }
                });
            })

What would be the solution to the problem? All the elements react on click (because their click event has been registered previously), except the one I have just dragged to the list.


Solution

  • change it like

     function initListClickEvent() {
         $("#list1 > li").click(function () {
            $(this).css("background-color", "blue");
            $(this).css("color", "white");
        });
            $("#list1 > li").trigger("click");
        }
    
        $(document).ready(initListClickEvent);
    
        $(function () {
            $("#list1").droppable({
                accept: 'li',
                drop: function (e, ui) {
                    initListClickEvent();
                }
            });
        });
    

    Edit

    If the elements are adding dynamically, you should use event delegation for that

    $(document).on("click","#list1 > li",function(){
       $(this).css("background-color", "blue");
            $(this).css("color", "white");
    });
    

    It helps you to attach handlers for the future elements