Select2's element displays for a second, then dissapears!

Hi! I got this problem with a wordpress plugin I’m working on. I tried using this on a local html page, and it works properly. Now, when I tried on a server with wordpress, I can see that it initializes, but after some miliseconds it gets replaced by the vanilla select menu. I don’t know what could be causing this. What do you fellas think?

edit: I am thinking the cause might have to do with something inside the wordpress theme, or just how I’m using it. Maybe it’s the fact that I’m targetting a ‘menu’ element is what’s causing the issue.

The first menu is how it’s looking with select2. That’s fine. The second menu on the picture is how it ends up looking - a normal select element.

[] And this is how the script looks like. Nothing complicated, just need to see it run properly first.

Any help on this issue would be greatly appreciated. Thanks, y’all!

I don’t know a lot about Wordpress, but I’m guessing that, some time after $('document').ready() fires, something in Wordpress (or in the Wordpress theme you’re using) redraws the DOM, thus erasing the extra HTML elements that the Select2 initialization code inserted into the DOM.

If you could figure out what’s causing the redraw (assuming that’s what’s actually happening), maybe that process fires an event that you could listen for and initialize your Select2 when that event fires. (Or maybe it allows you to specify a callback function that runs after the redraw. I’m really just guessing/hoping here…)

In the worst case you could try initializing your Select2 within a setTimeout() call with a sufficient (though not too long) delay. You would probably have to experiment to find an appropriate delay value, and it that value might differ for other users depending on their network speed, computer’s speed, or a host of other factors. So this really is a worst-case option.

Alternatively, if your Wordpress theme inserts some specific element on the page after $('document').ready() has fired, you could write some code to watch for that element to appear on the page (perhaps within a setInterval() call so it doesn’t poll continuously) and initialize the Select2 only after that element appears in the DOM.

Maybe the Wordpress documentation has some information about this (not about working with Select2 specifically, but about an event that Wordpress fires after it has finished updating/redrawing the DOM).

Finally, you could try googling “wordpress select2 plugin” and see if that produces any useful information.

Good luck!