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.

1 Like

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

1 Like

Get an Error with this setup:

The error/warning:

Okay, after changing the Block Type from ‘dynamic PHP’ to ‘ACF’ the slider is working in Backend also. The Block itself has no fields because it’s just a PHP Query Loop. But whatever, now it works.

Hi @MichelyWeb

ha strange! I always have it on Dynamic PHP. But i use it in a theme not a plugin. So that might be the issue. Good to hear it is working now! :wink: