bluzky / nice-select2

A lightweight vanilla javascript library that replaces native select elements with customizable dropdowns
https://bluzky.github.io/nice-select2/
MIT License
370 stars 61 forks source link

window.onclick in another javascript file causing problems for nice-select2's _onClicked handler #28

Closed remdragon closed 1 year ago

remdragon commented 2 years ago

I'm having difficulty integrating nice-select2 into a project.

I know this has to be a bug in my code and distilling it down to a simple reproducible example would be difficult. I'd be willing to pay for some support if it's available.

I have an async function that is dynamically generating html based on user input. It's async because some of the select controls need to call fetch() to get their content.

At the end of that function, it checks if any select2 controls were generated and triggers a setTimeout with a delay of 100. This was necessary because select2 couldn't even find the elements if I do it quicker.

Inside the setTimeout callback I'm triggering NiceSelect. I know it's at least partially working but the control transforms into a select2 styled control, but when I click on it, nothing happens and I get no errors in the console.

Here's the snippet where I invoke setTimeout:

        if( has_select2 )
        {
            setTimeout( function()
            {
                let options = { searchable: true }
                let els = Array.from( document.getElementsByClassName( 'ace_select2' ))
                for( let el of els )
                {
                    console.log( 'select2 binding: ', el )
                    NiceSelect.bind( el, options )
                }
            }, 100)
        }
remdragon commented 2 years ago

Further investigation has found that when I click the control, the _onClickedOutside() function is immediately getting invoked twice.

remdragon commented 2 years ago

This appears to be caused by an event handler in Aimara, but I'm not sure how or why yet

    window.onclick = function() {
        if (tree.contextMenuDiv!=null)
            tree.contextMenuDiv.style.display = 'none';
    }
remdragon commented 2 years ago

I was able to solve the problem by adding e.preventDefault() at the beginning of _onClicked():

NiceSelect.prototype._onClicked = function(e) {
    e.preventDefault() // <<<<< added this
    if (this.multiple) {