How to initialize JS inside of the Block Editor (PHP Block)

I have a slider block (created with Splide) which is a PHP Block that fetches a CPT.
On the frontend the Slider JS gets inizialized. But on the Backend it’s not working. The slides are hidden (aka not initialized JS).

I was able to get it working with a method mentioned in this GitHub comment. But as soon as the slider is used it gets hidden again.

How to solve this the right way?

Hi @MichelyWeb

You have to load the splide.js in the block so that it uses it in the back-end and front-end. The initialization code you can put also in the splide.js at the bottom. Since you can only load one js file in the block.

That should work. Been a while that i did it that way. I now am using Alpine.js to initialize the slider and that works great.

Guido

I am using the action enqueue_block_editor_assets for enqueueing assets manually. That way i am able to add multiple assets per block. Using the method you mentioned does not help (because the splide Script is loaded as a dependency).

Is there an alpine.js based slider you would recommend?

Ah oke yes manually that way is a good option. I use splide.js and alpine.js to initialize the slider. Alpine also has its own slider/carousel but i like splide and never really tried the alpine slider.

You can initialize it like this:

And i load the slider.js in the block. That is working great for me on front-end and back-end.

Thank you for the example code. I’ll try it that way next week.

1 Like