How do you target Bricks Elements by the unique ID correctly?

I’m working on building out a custom element (my first!) for a jQuery plugin that we use quite frequently and I was able to get everything up and running really quickly - however - I’m having an issue understanding the best way to run scripts that target individual elements.

The jQuery plugin I am integrating will break if you run the method on the same element twice, so I need to be targeting them based on the ID of the element on the off chance we might need multiple of this element on a single page.

I’ve got my enqueue_scripts() setup like so:

  public function enqueue_scripts() {
    
    wp_enqueue_script( 'lt-bricks-jquery-marquee', plugin_dir_url(__FILE__) . 'assets/jquery.marquee.min.js', ['jquery'], null, false );
    wp_enqueue_script( 'lt-bricks-jquery-marquee-func-'. $this->id .'', plugin_dir_url(__FILE__) . 'assets/lt-marquee.js', ['jquery'], null, false );
  	
    $script = "ltMarquee('#brxe-" . $this->id . "')";
    wp_add_inline_script('lt-bricks-jquery-marquee-func-'. $this->id .'', $script , 'after'); 
  	
  }

This works fine on the frontend but the scripts in the builder don’t run correctly, I’ve got this defined in the $scripts array:

public $scripts = ['ltMarquee'];

Is there a way I can pass $this->id to that function for the backend? Even though it works on the frontend I feel like I’m doing something wrong. :sweat_smile:

In enqueue_scripts(), if you have multiple marquee elements on the same page, it will load this same scripts multiple time, due to different handle.

enqueue like this

public function enqueue_scripts() {  
    wp_enqueue_script( 'lt-bricks-jquery-marquee', plugin_dir_url(__FILE__) . 'assets/jquery.marquee.min.js', ['jquery'], null, false );
    wp_enqueue_script( 'lt-bricks-jquery-marquee-func', plugin_dir_url(__FILE__) . 'assets/lt-marquee.js', ['jquery'], null, false );
}

in your lt-marquee.js. just do below, then ltMarquee will get call in Builder and Frontend

jQuery(document).ready(function () {
    ltMarquee();
});

function ltMarquee() {
    // replace the class of your marquee element
    jQuery('.brxe-marquee').each(function () {
		var $ele = jQuery(this);
		
        // your code here for each marquee elements
		// $ele.text('Hello'); or whatever logic you want
    });
}
1 Like

That makes a ton of sense, I was too hyper focused on trying to solve it in the PHP file.

Appreciate it!