SOLVED: Custom Element Script runs in builder but isn't running on front end. What am I doing wrong?

Hey,

Working on creating a custom element that runs some javascript. The code runs in the builder, but I can’t seem to get it to work on the front end. I was hoping someone could point out my error. I’ll try to include all the relevant bits below, but let me know if it’s not enough:

Element PHP:

class Prefix_Custom_Element extends \Bricks\Element {
	// Element properties
	public $category     = 'media';
	public $name         = 'custom-element';
	public $icon         = 'fa-brands fa-js-square';
	public $scripts      = ['customElementScript'];
...
public function enqueue_scripts() {
		wp_enqueue_script( 'custom-element-script');
	}
...
}

Element Script:

function customElementScript() {
	console.log('test');
}

You’d need to add an event for when the function is going to run, for eg on DOMContentLoaded

document.addEventListener("DOMContentLoaded",function(e){
  customElementScript()
})

Hey,

I appreciate your response. I think that’s essentially what bricks does for you when defining the “public $scripts = [‘customElementScript’];” variable. Or at least I assume it is because it automatically calls my script in the back end.

Do you have an example of where I can find this being called in an existing element that I can reference?

Only in the builder.

In Bricks theme, bricks/assets/js/bricks.min.js at the bottom. All of the functions are being called on DOMContentLoaded for the front end.

2 Likes

Perfect! That’s exactly what I was looking for! You’re a wizard! :slight_smile:

I was looking through the bricks.min.js as well as some other free bricks plugins and never bothered to scroll to the bottom. I do feel a little bit silly now. :man_facepalming:

Probably worth a mention in the docs. I spent about an hour because currently the docs states this:

public $scripts = ['prefixElementTest']; // Script(s) run when element is rendered on frontend or updated in builder

The ‘on frontend’ says to me that I needn’t do anything else but refer to the function name here.