Is there a 'right way' to run JS in the WP Block editor when a block style is selected?
I've searched through documentation and google but can't see an example of anyone running a JS script on a block style.
Essentially, I want to inject two elements around a core/group block, if it has a particular style.
My code works just fine on the front end, but in the backend, I can only get it working on a page refresh, after the block style is selected. Here is what i've got so far:
Registerd by block style with php:
register_block_style(
'core/group',
array(
'name' => 'shape-pattern-1',
'label' => 'Shape Pattern 1'
)
);
Function I want to run when style is in use
var initialiseShapePatterns = function($block) {
$block.prepend('<span class="shape-before"></span>');
$block.append('<span class="shape-after"></span>');
$(window).on('load scroll', function() {
if( $block.isInViewport() ) {
$block.addClass('animate');
} else {
$block.removeClass('animate');
}
});
}
Calling function on front-end (working)
$(document).ready(function() {
$('.is-style-shape-pattern-1, .is-style-shape-pattern-2, .is-style-shape-pattern-3').each(function() {
initialiseShapePatterns( $(this) );
});
});
Calling function in block editor (only works if style is already selected on page load)
if( wp.domReady ) {
wp.domReady(function() {
$('.is-style-shape-pattern-1, .is-style-shape-pattern-2, .is-style-shape-pattern-3').each(function() {
initialiseShapePatterns( $(this) );
});
});
}
I get that I'm only telling it to run when the dom is loaded, but I can't find anything in the documentation about running code on style select.
Any ideas?
In jquery, you can add event listners, which will trigger an action when a event happens.
The following code snippet will execute when a button with the id 'myButtonId' is clicked.
$( "#myButtonId" ).click(function() {
//myButtonId was clicked.
$('.is-style-shape-pattern-1, .is-style-shape-pattern-2, .is-style-shape-pattern-3').each(function() {
initialiseShapePatterns( $(this) );
});
});
You will need to set the id of the button which you want to trigger this function. You can do this with the html id attribute
<button id='myButtonId'> Button Text </button>
In wordpress you can add custom HTML.You mentioned blocks so i assume you are using the gutenburg block editor. This means that you can find the block 'custom HTML' and then put that html button in the custom code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With