Blur on Select2 is fired to often

jquery, jquery-select2

Solution

Well that plugin has custom made events so it's not possible to "catch" the `blur` event because it creates it's own while adding elements to the selection and while opening/closing the options drop-down.

Here is a workaround that might work, but needs to be fine-tuned depending on the rest of the code you might have.

I found a class `.select2-container-active` that only exist when the `select2` is focused. But this `class` comes and goes on each new selection. So what I did was a `setTimeout` that waits for the `select2` code to work. In case the `class` is still there, then it's still focused in the `select2`. If the `class` is not there anymore it will think it was a "normal" `blur` and run the log function. This gives a small delay, but `select2` is the guilty one for that :)

test.on("select2-blur", function (e) {
    setTimeout(function () {
        var active = $('#s2id_test').hasClass('select2-container-active');
        if (active) {
            return false;
        }
        log("Blur");
    }, 300);
});

Fiddle

Problem

I am implementing an Select2 where the user should be able to select multiple items, when the focus is lost from the field I want to save the items selected. I tried to use the select2-blur event, but it is fired to often. It fires as soon as an option is selected. The select2 is created with: ``` $(test).select2({ data:[ {id:0,text:"Item 1"}, {id:1,text:"Item 2"}, {id:2,text:"Item 3"}, {id:3,text:"Item 4"}, {id:4,text:"Intem 5"} ], multiple: true, width: "300px" }); $(test).on("select2-blur", function(e) { doStuffOnLostFocus();}); ``` I created a fiddle where you can see the blur event being triggered on several occasions more than when focus are lost on the select2 control: http://jsfiddle.net/Wp8Wf/ Anyone got some good ideas on how to do stuff only when the user moves away from the select2?

Original source