Skip to content
Arrow keys to move, Enter to open, Esc to closeAll results
Design and Builders · Guides

Custom CSS and JavaScript in Bricks Builder: Scoped, Fast and Safe

Where custom CSS and JavaScript belong in Bricks Builder, how to scope them with the root placeholder, and eight copy-ready patterns that stay fast and safe.

Written by
WPresident Editorial
Topic
Design and Builders

Every Bricks site eventually needs a few lines of code that the style controls do not offer: a hover effect with a particular easing, a line clamp, a sticky column, a button that copies a coupon code. Bricks gives you several places to put that code, and that is where the trouble starts. The code itself is rarely the problem. The problem is where it lives, what it can reach, and when it runs. A snippet pasted into the global stylesheet with the selector .card quietly restyles every card on the site. A script in the footer field runs on two hundred pages that never needed it. A copy button that works on first load stops working after a Load more click. A rule that looks perfect in the builder loses to a theme style on the live page.

The single most important idea in this tutorial is scope. Every piece of custom code has a scope (one element, one page, the whole site) and a lifetime (when it runs, and whether it runs again when new content arrives). If you choose the smallest scope that works, express it with the placeholder Bricks provides for exactly this purpose, and make your JavaScript check that its target exists before it does anything, most of the usual problems never appear. Scoped code is also faster, because a page only receives the code it uses, and safer, because a typo on one element cannot break the rest of the site.

The tutorial starts with a map of the places custom code can live in Bricks and a rule for choosing between them. Then it covers the element-level placeholder, %root%, with the first working snippet, a hover card. After that comes the part that decides whether your CSS wins: specificity, the cascade layers Bricks uses, and how to write rules that are easy to override later. Four more CSS patterns follow (an aspect-ratio box, a line clamp, a container-query component and a sticky sidebar with a smooth-scroll offset), each with a rendered example so you can see what the code produces.

The JavaScript half covers loading scripts only where they are needed, running at the right moment (on DOM ready, and again after Bricks loads new items through Load more, infinite scroll, filters or popups), and three more patterns: a copy-to-clipboard button, a lazy script loader and a data-attribute toggle. It ends with debugging in the browser, a symptom-and-cause table, and a short section on safety and performance, including the code-execution switch that protects PHP in Bricks and why plain CSS and JavaScript fields are a different case.

Some honest boundaries. This is a general guide built from the public Bricks documentation and from standard browser features, not a test report, and it contains no benchmark numbers. Bricks changes between versions, so wherever a control or setting name appears here it is one the documentation names; if your installed version looks different, trust the Bricks documentation and the Bricks Academy over this page. The snippets use plain modern CSS and JavaScript with no library, but they are examples to adapt: paste them into a staging copy first, check them with your own content, and keep the browser developer tools open while you do. Colors, class names, data attributes and sizes are placeholders for you to replace.

You do not need to know PHP for anything in this tutorial. You need to be comfortable reading a CSS rule, and willing to open the browser inspector when something does not behave. That habit, more than any snippet, is what separates a site that is pleasant to maintain from one where nobody dares touch the custom code.

Key points

  • Pick the smallest scope that works: element or class CSS first, page-level code for one page or template, global code only for things that truly apply everywhere.
  • Write element CSS against the %root% placeholder so Bricks turns it into the right selector, and keep the rule low in specificity so it stays easy to override.
  • Bricks places its default styles in a cascade layer, so your unlayered custom CSS normally wins without !important; the browser Styles pane tells you for certain.
  • Load JavaScript only on pages that contain its target, prefer defer or a loader that waits for the element to approach the viewport, and never depend on jQuery.
  • Run scripts on DOM ready and again when Bricks adds nodes after AJAX events, using event delegation or the documented Bricks events instead of one-off listeners.
  • PHP and executable code are gated by code execution and signatures in Bricks; plain CSS and JavaScript are not, which makes the capability to edit them worth guarding too.

Choose the smallest scope that works

Bricks has more than one place for custom code, and the choice is not a matter of taste. According to the Bricks documentation the main locations are: the CSS control group on an element or global class (in the Style tab), the Stylesheet group inside a Theme Style, the Custom Code group in the page settings, the global Custom code screen under the Bricks settings, and the Code element that you place at a particular point in the page output. You can also load files from a child theme or a small site plugin. Each location trades reach against cost.

Element and class CSS is the narrowest. It belongs to one element or one global class, it is written with the %root% placeholder, and when the element is deleted the CSS goes with it. Page-level code is local to the page or template you are editing: the page settings offer a Custom CSS field, which Bricks prints inline in the head, plus header scripts, body (header) scripts and body (footer) scripts. The script fields only appear for users who are allowed to add unfiltered HTML, which is a useful reminder that these fields are powerful. Global code, in the Bricks settings under Custom code, is printed on every page: the CSS at the end of the head, and scripts in three document locations. The documentation says to wrap the JavaScript you enter in the global script fields in script tags, and it is safest to do the same in the page fields.

The Theme Style stylesheet group sits in between. Its CSS is output with that Theme Style and therefore follows the Theme Style’s conditions, which makes it a good home for CSS that belongs to one design context, such as everything that styles the blog template. It is plain CSS, so write your own media queries there; it does not get the breakpoint handling of the generated controls.

A practical rule works in nearly every case. If the code styles one element or one reusable component, put it on that element or on its global class. If the code is needed on exactly one page or template, put it in that page’s custom code. If it is needed on many pages but not all, load it conditionally from a child theme or a small plugin, using a check such as is_singular() or a template test. Only code that is genuinely site-wide, such as an analytics tag or a base utility, belongs in the global fields. One caution from the Bricks documentation itself: page-level code is local to its page, so it is the wrong place for behavior you want to reuse across the site.

The cost side matters as much as the scope side. With the default inline CSS loading method, global custom CSS is part of the HTML of every response, so every kilobyte you add there is paid on every page view by every visitor. Page-level CSS is paid only by that page. Setting the CSS loading method to external files under the Performance settings lets browsers cache the generated stylesheets, which helps with repeat visits, but it does not change which page receives which rules. Scope first, then tune delivery.

There is a quieter benefit too: scoped code is easy to find. When a client asks why the testimonial cards have a different shadow, “it is in the CSS control of that card’s global class” is a better answer than a search through four thousand lines of global CSS. Name your global classes clearly, keep a short comment at the top of every snippet saying what it is for, and the custom code stays an asset rather than a liability.

Where should this code live?

How much of the site does the code need to reach?
One element, or one reusable componentElement or global class CSS in the Style tab, written against %root%.
One page or template onlyPage settings, Custom Code group: page CSS and the body footer script field.
Several pages, not all of themEnqueue from a child theme or site plugin with a condition for the pages that need it.
Every page without exceptionGlobal custom code in the Bricks settings, kept as small as possible.
A decision rule for picking the narrowest Bricks location that still reaches everything the code must affect.

Element CSS and the %root% placeholder: a scoped hover card

To add CSS to a single element, select it, open the Style tab and expand the CSS control group. The editor accepts ordinary CSS and one special token: %root%. Bricks automatically converts it to the selector of the element you are editing, or to the class selector when you are editing a global class. The documentation adds two conveniences: typing r and pressing Tab inserts the placeholder, and the editor understands Emmet abbreviations such as m10 for margin: 10px.

The reason this matters is that you never type an element ID yourself. Bricks generates IDs, and an ID you copy from the inspector changes meaning the moment you duplicate or move the element. Because %root% is resolved at output time, the same snippet can be pasted onto another element and will target that element. If the CSS lives on a global class, renaming the class also updates the placeholder-based CSS stored in it, according to the class documentation. That is the main reason to write class-level custom CSS with %root% rather than with a hand-typed class name.

Here is the first pattern, a card that lifts slightly on hover and on keyboard focus. Put it on the card container, or better, on a global class used by every card.

%root% {
  --card-lift: -4px;
  position: relative;
  border: 1px solid #d9dee5;
  border-radius: 12px;
  background: #ffffff;
  transition: transform 180ms ease, box-shadow 180ms ease, border-color 180ms ease;
}

%root%:hover,
%root%:focus-within {
  transform: translateY(var(--card-lift));
  border-color: #2563eb;
  box-shadow: 0 12px 28px rgb(15 23 42 / 0.12);
}

/* Make the whole card clickable through its main link */
%root% a::after {
  content: "";
  position: absolute;
  inset: 0;
}

@media (prefers-reduced-motion: reduce) {
  %root% { transition: none; }
  %root%:hover,
  %root%:focus-within { transform: none; }
}

Reading it line by line: the custom property --card-lift keeps the one number you are likely to tune at the top of the rule. The transition lists the properties that change instead of using all, which avoids animating things you did not intend. :focus-within applies the same lift when any link or button inside the card has keyboard focus, so keyboard users get the feedback that mouse users get. The a::after rule stretches the link’s clickable area over the whole card, a common pattern; it assumes the card has one main link, so if yours has several, apply it to the heading link only. The reduced-motion block switches off the movement for visitors who have asked their system for less animation.

Two cautions. First, if you also set a transform, border or shadow in the style controls of the same element, the two sources compete. The CSS Sync option in the Bricks settings is documented as experimental, and it says that when the same property is set both in custom CSS and in a style control, the custom CSS takes precedence. Pick one home per property. Second, elements inside a query loop are a special case. The Bricks Interactions documentation notes that on the front end such elements do not get their automatic element ID unless you set a CSS ID yourself. After you place a snippet on a loop item, open the page source or the inspector, find the CSS Bricks printed, and confirm that its selector really matches the markup. If it does not, move the CSS to a global class, which matches every card by class and is the cleaner design in any case.

Rendered output of the code above
Two identical cards side by side, the right one lifted with a blue border and a larger shadow to show the hover state
A plain HTML and CSS render of the hover card technique, showing the resting and the hover state side by side; it is not a screenshot of the Bricks editor.

Specificity, cascade layers and the order rules are applied

Whether your CSS wins is decided by the cascade, and three things feed it: layers, specificity and order. Bricks changed the first of these in a way that helps you. The Bricks documentation describes a layer stack in which Bricks’ own default styles and element CSS live in a cascade layer named bricks, with an empty sub-layer named bricks.reset underneath as a safety net. Under the cascade rules of the browser, declarations that are not in any layer beat declarations inside layers, regardless of selector specificity. In current versions Bricks enables this by default; the Performance settings contain a legacy option to turn it off, which the documentation strongly discourages. Check the state of that option on your site before you rely on the behavior.

The practical outcome is that a plain, unlayered rule you write in custom CSS can override a Bricks default without a heavier selector and without !important. The docs give the standard example: a default rule such as [class*="brxe-"] { max-width: 100% } used to beat a simple div selector because an attribute selector is more specific than a type selector. With layers, your div { max-width: 400px } wins anyway. One exception is documented: if a default rule inside the layer uses !important, the order flips, and the bricks.reset sub-layer exists for the rare case where you need to answer that.

Layers only settle things between layered and unlayered styles. Between two unlayered rules, specificity decides first and source order decides ties. Specificity is counted as three numbers: IDs, then classes, attributes and pseudo-classes, then type selectors. An element-ID selector such as #brxe-abc123 beats any number of classes, and the Bricks class documentation states the practical consequence: element ID styles are more specific than global class styles, so a property set on both usually resolves in favor of the element. Bricks also chains a global class with the element-type class on the same element (for example .my-class.brxe-button), which raises the selector’s weight a little; a Performance setting called Disable class chaining removes that chaining for edge cases where it clashes with third-party CSS.

Theme Styles are the other thing to place on your mental map. The Theme Styles documentation describes them as baseline styles, output before more specific Bricks-managed CSS such as global classes, page settings, template content, element settings and popup styles, and it notes that custom CSS with a stronger selector or later output can override them. If a rule from your custom CSS seems to lose to a Theme Style, the cause is nearly always a more specific selector in the Theme Style, a more specific selector on a global class, or the same property set on the element ID.

Habits that keep your own CSS easy to live with follow from this. Write one class-level selector per rule and avoid chains of descendants. Keep the weight of base rules low, and use :where() when you want a selector to contribute zero specificity, as in :where(%root%) a { text-decoration: none }; remember that :is() takes the specificity of its most specific argument, so it does not lower weight. Reserve !important for beating inline styles or third-party code you cannot edit. And when a property will not apply, do not add selectors until it does; open the Styles pane in the browser, find your rule, and see what struck it through. The figure below is a simplified ladder, not a guarantee, and the inspector is the authority for any specific page.

A simplified cascade ladder, strongest first

Declarations marked !importantAlso flips the order inside layers; use sparingly.
Element ID stylesProperties set on the element itself, heavier than a class.
Your custom CSSUnlayered, so it beats Bricks defaults; wins ties by coming later.
Global class stylesChained with the element class unless chaining is disabled.
Theme StylesOutput first as the baseline for the site.
Bricks defaults in the bricks layerLayered, so any unlayered rule overrides them.
A mental model for which source tends to win a conflict; confirm any specific case in the browser Styles pane.
Rendered output of the code above
Four rows, each showing two CSS rules and a bar for the resulting width of one box. With layers on, the box is 400 pixels wide because the plain div rule wins. With layers off, the box is full width because the attribute selector is more specific. With an important default inside the layer, the box is full width. With an important rule in the bricks.reset sub-layer, the box is 400 pixels wide again.
A plain HTML and CSS render of the documented cascade-layer example, drawn with real layered CSS in the browser, not a screenshot of the Bricks editor.

Aspect-ratio boxes and line clamps for tidy cards

Two small CSS features remove a surprising amount of fiddly layout work in card grids: aspect-ratio and the line clamp. Both are best attached to a global class so every card in the design system behaves the same way.

The aspect-ratio box gives a media wrapper a fixed proportion regardless of the image inside it. The browser reserves the box before the image has loaded, which prevents the layout from jumping when the file arrives, and that matters for the layout-shift part of Core Web Vitals. Put this on the wrapper element that contains your image or video:

%root% {
  aspect-ratio: 16 / 9;
  width: 100%;
  overflow: hidden;
  border-radius: 12px;
  background: #e5e7eb;
}

%root% img,
%root% video {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

%root% iframe {
  width: 100%;
  height: 100%;
  border: 0;
}

The aspect-ratio value is width over height, so 16 / 9 gives a wide thumbnail and 1 / 1 a square. The grey background shows while the image loads. Inside the box, object-fit: cover fills the area and crops the overflow instead of stretching the picture; use contain when cropping would remove something important, such as a logo. The iframe rule makes an embedded video fill the same box, because object-fit has no effect on iframes. Before writing this, look at the element’s own controls: if the element already offers a ratio setting you are happy with, use it, and keep this CSS for wrappers, backgrounds and non-image content.

The line clamp trims a block of text to a fixed number of lines and adds an ellipsis, so cards in a row stay the same height whatever the editor typed into the excerpt:

%root% {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  overflow: hidden;
  line-height: 1.5;
  min-height: calc(3 * 1.5em);
}

The prefixed properties are still the form that works everywhere; the unprefixed line-clamp is the standard name and is harmless where it is not yet understood. The element must be display: -webkit-box for the clamp to apply, which is why this rule belongs on a text element or a plain Div and not on a flex layout element. The min-height line equals three lines at a line height of 1.5, so short excerpts still occupy the same space as long ones; if you change the clamp count or line height, change both numbers together. The clamp only hides overflow visually. The full text is still in the page, which keeps it available to search engines and screen readers, so do not use it to hide content you do not want published.

Rendered output of the code above
Three boxes with 16 to 9, 4 to 3 and 1 to 1 proportions, and two paragraphs, one unclamped and one cut to three lines with an ellipsis
A plain HTML and CSS render of aspect-ratio boxes and a three-line clamp, not a screenshot of the Bricks editor.

Container queries: components that respond to their own width

Bricks breakpoints, like media queries in general, respond to the width of the viewport. That is the wrong measuring stick for a reusable card. The same card may sit in a wide main column on one page and in a narrow sidebar on another, at exactly the same viewport width, and it needs a different layout in each place. Container queries solve this: you mark an ancestor as a query container, and rules inside @container respond to that ancestor’s width instead of the screen’s.

The setup has two halves. The wrapper declares itself a container, and the component’s own layout rules live inside the query:

%root% {
  container-type: inline-size;
  container-name: card;
  width: 100%;
}

%root% .media-card {
  display: grid;
  gap: 1rem;
}

@container card (min-width: 30rem) {
  %root% .media-card {
    grid-template-columns: 11rem 1fr;
    align-items: center;
  }
}

Here container-type: inline-size turns the wrapper into a container that can be queried by width, and container-name lets the query target this container specifically, which matters once containers are nested. By default the card stacks: image above text. When the wrapper is at least thirty rem wide, the card becomes a two-column grid with the image on the left. Rem units follow the root font size, which keeps the threshold stable if you change the card’s own text size.

Three details trip people up. First, a container query styles descendants of the container, never the container itself. That is why the wrapper and the layout element are different elements in the snippet; if you try to put both on one element, the query has nothing to apply to. Second, inline-size containment means the container’s width is computed without looking at its content. If the wrapper is a flex item sized by its content, or an inline-level box, it can collapse to nothing. Give it an explicit width, such as width: 100% or a flex-grow, as the snippet does. Third, Bricks substitutes %root% for you, but after saving, view the page source once to confirm that the placeholder was replaced inside the at-rule as well as outside it; if it was not, write the rule against a global class name instead.

When should you use a container query rather than a Bricks breakpoint? Use breakpoints for page-level decisions: hide the sidebar below a width, change the number of columns of the whole grid, switch the header to a mobile layout. Use container queries for component-level decisions: a card, a pricing box or a testimonial that should adapt to the space it is given. Mixing both is normal. The grid decides how wide each cell is, and the card inside decides how to fill that cell.

Container queries are supported by all current major browsers, and Bricks itself writes modern CSS (the Bricks documentation says its output already uses features such as :where() and @layer) while stating that your own CSS is yours to write with whatever fallbacks you need. If your audience includes very old browsers, the stacked layout is a sensible default that still works without the query, which is the reason the snippet writes the narrow layout first.

Rendered output of the code above
The same media card shown in a narrow container, stacked with the image above the text, and in a wide container, with the image on the left and text on the right
A plain HTML and CSS render in which the same card adapts to two container widths using a real container query, not a screenshot of the Bricks editor.

A sticky sidebar and a smooth-scroll offset that clears the header

Two layout behaviors cause more support questions than almost any other CSS: a sticky sidebar that refuses to stick, and an anchor link that scrolls the target underneath a fixed header. Both have short, reliable fixes.

Start with the sidebar. Put this on the sidebar element, which should be a sibling of your main content column inside a row container:

%root% {
  position: sticky;
  top: calc(var(--header-height, 72px) + 1.5rem);
  align-self: flex-start;
  max-height: calc(100dvh - var(--header-height, 72px) - 3rem);
  overflow-y: auto;
}

The top value is the distance from the top of the viewport at which the element sticks. The custom property stands for the height of your fixed or sticky header, with 72 pixels as a stand-in you replace with your real value; the extra 1.5rem leaves some air. align-self: flex-start is the line people forget. Bricks layout containers are built on flexbox, and flex items stretch to the full height of the row by default. A sticky element needs room to travel inside its parent, and a stretched sidebar has exactly as much height as its parent, so it has nowhere to go. Aligning it to the start lets it be as tall as its own content. The last two lines handle a sidebar taller than the screen: it gets a maximum height and scrolls internally rather than hiding its bottom half.

If the sidebar still does not stick, look for the real culprit, which is nearly always an ancestor with overflow set to anything other than visible. A sticky element is positioned relative to its nearest scrolling ancestor, and an overflow: hidden wrapper, even one added to clip a decorative shape, becomes that ancestor and silently disables the behavior. Walk up the tree in the inspector, element by element, and check the computed overflow value. The second culprit is a parent that is no taller than the sidebar, which again leaves no travel distance.

Now the anchor offset. When a visitor follows a link to an element ID, the browser scrolls that element to the very top of the viewport, which is under a fixed header. Instead of adding offset hacks to every link, tell the browser once. This belongs in the global custom CSS, because it applies to the whole document:

html {
  scroll-behavior: smooth;
  scroll-padding-top: calc(var(--header-height, 72px) + 1rem);
}

@media (prefers-reduced-motion: reduce) {
  html { scroll-behavior: auto; }
}

scroll-padding-top reserves space at the top of the scrollport for every anchor jump, so the target lands just below the header. scroll-behavior: smooth animates the jump, and the media query turns the animation off for visitors who prefer reduced motion. If only a few targets need a different gap, set scroll-margin-top on those elements instead. Remember that an element can only be an anchor target if it has an ID: set a CSS ID in the element’s settings, and keep IDs unique, which needs extra care inside query loops. When the scroll is triggered by a Bricks interaction instead of a link, the Scroll to action has its own offset field in pixels, documented in the Interactions article, so you can skip the CSS and set the number there.

A still image cannot show sticking, which only happens while you scroll, but it can show the cause of the most common failure: the height of the sidebar. The figure below draws two rows with the same sticky rule, one with the flexbox default and one with align-self: flex-start.

Rendered output of the code above
Two flex rows, each with a tall main column and a narrow blue sidebar. In the left row the sidebar stretches to the full height of the row. In the right row the sidebar is only as tall as its four links, and a hatched area below it shows the room it can travel through while sticky.
A plain HTML and CSS render comparing a stretched sidebar with one set to flex-start, which shows the room to travel but not the scrolling itself, not a screenshot of the Bricks editor.

Load JavaScript only on the pages that need it

JavaScript is the most expensive thing you can add to a page, byte for byte, because the browser has to download it, parse it and run it on the main thread. The fix is not cleverness, it is delivery: send each script only to the pages that use it, and let the browser fetch it without blocking the page.

There are three common routes in Bricks, and the figure compares the two you will use most. The first is the script fields in the page settings, where the Custom Code group offers header scripts, body (header) scripts and body (footer) scripts for the page or template you are editing. The footer field is the right default: the script runs after the markup it needs has been parsed. The second is the Code element, which has a JavaScript editor whose content Bricks wraps in script tags for you; because the element sits where you place it, the script travels with the component, and deleting the component removes the script. The Bricks documentation lists separate conditions for when its editors are available, so check the Code element article for your user. The third route is a file in your child theme or a small site plugin, enqueued with a condition, which is what you want for anything larger than a screenful or used on several pages.

Here is a conditional enqueue for a script file in a child theme. The Bricks child theme documentation uses the check against bricks_is_builder_main() so that your files load on the front end and in the builder canvas but not in the builder panel itself.

<?php
add_action( 'wp_enqueue_scripts', function () {
	// Keep custom code out of the builder panel.
	if ( bricks_is_builder_main() ) {
		return;
	}

	// Only pages that contain the copy buttons.
	if ( ! is_singular( 'post' ) && ! is_page( 'coupons' ) ) {
		return;
	}

	$file = get_stylesheet_directory() . '/js/copy-button.js';
	if ( ! file_exists( $file ) ) {
		return;
	}

	wp_enqueue_script(
		'child-copy-button',
		get_stylesheet_directory_uri() . '/js/copy-button.js',
		array(),
		(string) filemtime( $file ),
		array(
			'strategy'  => 'defer',
			'in_footer' => true,
		)
	);
}, 20 );

This goes in the child theme’s functions.php. The condition lists the post type and the page slug that use the script; replace both with your own. The version argument is the file’s modification time, so browsers fetch a fresh copy whenever you edit it and cache it otherwise. The strategy option, available in WordPress since version 6.3, makes the script tag defer, which downloads in parallel and runs after the document is parsed without blocking rendering. A later priority such as 20 simply keeps your enqueue after most theme and plugin enqueues, which makes the order predictable.

Whichever route you choose, give the script a second line of defense: a cheap guard at the top that exits when its target is not on the page. A script that begins with if (!document.querySelector('[data-copy]')) return; costs almost nothing on pages without copy buttons and cannot throw errors there. Write plain JavaScript. Everything jQuery usually does has a direct equivalent: querySelectorAll for selecting, classList for classes, closest for walking up the tree, dataset or getAttribute for data, fetch for requests, and one delegated addEventListener instead of many bound handlers. Not depending on a library means one less thing that can be absent, deferred or removed by an optimization setting.

Page script field or child-theme file

Page settings script fieldEnqueued file in a child theme
ReachThat page or template onlyAny pages your condition matches
Where it is editedInside the builderIn a code editor, in a file
Browser cachingPart of the page HTMLCached as a static file
Version controlStored with the page dataReviewable and revertible in a repository
Best forShort, page-specific glueReusable behavior and larger scripts
Two ways to deliver the same script, compared on the points that usually decide the choice.

Run at the right moment: DOM ready, then again after Bricks adds content

A script has two timing problems to solve. The first is the page load: the elements the script wants must exist when it looks for them. The second is the page after load: Bricks can add new markup at any time through Load more, infinite scroll, AJAX pagination, query filters, live search and popups, and a script that attached listeners once at load will not see any of it.

For the first problem, use a tiny ready helper rather than assuming where your script is placed. A script in the head runs before the body exists, a script in the footer runs after it, and a deferred script runs after parsing but before the page has fully loaded.

function ready(fn) {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', fn, { once: true });
  } else {
    fn();
  }
}

If the document is still loading, the function waits for DOMContentLoaded; otherwise it runs immediately. The once option removes the listener after the first call. This is safe in every placement, so you never have to think about it again.

For the second problem there are two strategies, and you should prefer the first. Event delegation attaches one listener to the document and checks what was clicked at the moment of the event. Because the listener is not bound to individual elements, it keeps working for elements that were added later or replaced. It suits every click-driven behavior, including the copy button and the toggle later in this tutorial. When a behavior needs per-element setup, such as creating an observer, starting a third-party library or measuring sizes, use the second strategy: an idempotent init function that Bricks events call again whenever new nodes appear.

(function () {
  function init() {
    document.querySelectorAll('[data-fancy]:not([data-fancy-ready])').forEach(function (el) {
      el.setAttribute('data-fancy-ready', '');
      // Per-element setup goes here.
    });
  }

  ready(init);
  document.addEventListener('bricks/ajax/nodes_added', init);
  document.addEventListener('bricks/ajax/popup/loaded', init);
})();

The selector skips elements that already carry the data-fancy-ready marker, so running init ten times sets each element up once. That property, being safe to call repeatedly, is the whole trick. The snippet assumes the ready helper from the previous block is defined above it. The two event names come from the Bricks article on custom JavaScript events. bricks/ajax/nodes_added is documented as emitted after Bricks adds new AJAX result nodes to the DOM, and its detail carries the queryId of the loop that changed. bricks/ajax/popup/loaded fires after AJAX popup content has been added. Re-scanning the whole document is cheap for a handful of elements; if you have many, read the query id from event.detail and scan only that loop.

The order of events matters when you choose which to listen to. Bricks documents the sequences: for a query filter request it is bricks/ajax/start, bricks/ajax/end, bricks/ajax/query_result/completed, bricks/ajax/nodes_added and finally bricks/ajax/query_result/displayed. For infinite scroll and standalone AJAX pagination the sequence is start, nodes added, end, and then a completed event specific to the feature. The Bricks notes add a warning worth remembering: the pagination completed event is only emitted for standalone AJAX pagination, and when a Pagination element targets a loop with Query Filters, you must listen to the filter events instead. Listening to nodes_added avoids most of this, since it fires in every case where new nodes arrive.

A last option needs no listener at all. Bricks Interactions include a JavaScript (Function) action that calls a function you have defined on the global window object, with an Arguments repeater whose %brx% placeholder passes the interaction context, including the target element. Pair it with a trigger such as content loaded or a click, and the timing is Bricks’ problem. Only globally scoped functions can be called, so expose one object with your helpers and nothing else.

What fires when a query filter updates the page

bricks/ajax/startThe request is about to be made; a good moment to show a loading state.
bricks/ajax/endThe AJAX call has finished.
bricks/ajax/query_result/completedThe filter request is complete.
bricks/ajax/nodes_addedNew result nodes are in the DOM; run per-element setup here.
bricks/ajax/query_result/displayedAll filtered results have been added to the page.
The documented order of Bricks JavaScript events for an AJAX query filter request; initialise new elements on the nodes added event.

Copy to clipboard and a lazy script loader

Two JavaScript patterns that cover a lot of real pages. The first is a copy button for coupon codes, shortcodes or terminal commands. The second loads a heavy third-party script only when the visitor is about to see the thing that needs it.

For the copy button, add a Button element and give it a custom attribute. Bricks lets you add attributes under the Style tab’s Attributes group, with a name and a value, and the value can come from dynamic data. Name it data-copy and set the value to the text to copy. Add a second attribute, aria-live with the value polite, so that assistive technology announces the label change. The script is delegated, so it works for buttons inside query loops and for buttons that arrive later.

(function () {
  function copyText(text) {
    if (navigator.clipboard && window.isSecureContext) {
      return navigator.clipboard.writeText(text);
    }
    return new Promise(function (resolve, reject) {
      var area = document.createElement('textarea');
      area.value = text;
      area.setAttribute('readonly', '');
      area.style.position = 'fixed';
      area.style.opacity = '0';
      document.body.appendChild(area);
      area.select();
      var ok = false;
      try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
      document.body.removeChild(area);
      if (ok) { resolve(); } else { reject(new Error('Copy failed')); }
    });
  }

  document.addEventListener('click', function (event) {
    var button = event.target.closest('[data-copy]');
    if (!button) { return; }
    var label = button.querySelector('[data-copy-label]') || button;
    var original = label.textContent;
    copyText(button.getAttribute('data-copy')).then(function () {
      label.textContent = 'Copied';
    }).catch(function () {
      label.textContent = 'Press Ctrl+C to copy';
    }).then(function () {
      window.setTimeout(function () { label.textContent = original; }, 2000);
    });
  });
})();

The helper prefers the asynchronous Clipboard API, which browsers only expose on secure (HTTPS) pages and in response to a user gesture, which a click is. If that is unavailable, it falls back to a hidden textarea and execCommand, an old method that is deprecated but still the practical fallback. The click handler finds the nearest element with data-copy, swaps the label to confirm, and restores it after two seconds. The two-step then and catch chain handles failure gracefully instead of leaving the button stuck. If your button has an icon, wrap the visible words in an inner element carrying data-copy-label, so replacing the text does not delete the icon.

The lazy loader keeps a library such as a chart, map or video player out of the initial page weight. An element declares the file it needs with data-load-script, and an IntersectionObserver loads the file when the element is within 300 pixels of the viewport.

(function () {
  var targets = document.querySelectorAll('[data-load-script]');
  if (!targets.length) { return; }

  var allowed = [location.origin, 'https://cdn.example.com'];
  var requests = new Map();

  function isAllowed(src) {
    try {
      return allowed.indexOf(new URL(src, location.href).origin) !== -1;
    } catch (e) {
      return false;
    }
  }

  function load(src) {
    if (requests.has(src)) { return requests.get(src); }
    var request = new Promise(function (resolve, reject) {
      var tag = document.createElement('script');
      tag.src = src;
      tag.async = true;
      tag.onload = resolve;
      tag.onerror = function () { requests.delete(src); reject(new Error('Could not load ' + src)); };
      document.head.appendChild(tag);
    });
    requests.set(src, request);
    return request;
  }

  function start(el) {
    var src = el.getAttribute('data-load-script');
    if (!isAllowed(src)) { return; }
    load(src).then(function () {
      el.dispatchEvent(new CustomEvent('script:loaded', { bubbles: true }));
    }).catch(function (error) { console.warn(error.message); });
  }

  if (!('IntersectionObserver' in window)) {
    targets.forEach(start);
    return;
  }

  var observer = new IntersectionObserver(function (entries) {
    entries.forEach(function (entry) {
      if (entry.isIntersecting) {
        observer.unobserve(entry.target);
        start(entry.target);
      }
    });
  }, { rootMargin: '300px 0px' });

  targets.forEach(function (el) { observer.observe(el); });
})();

Three details deserve a sentence each. The requests object remembers every script already requested, so ten charts on one page trigger one download. The allowed list is a security measure, not decoration: a loader that fetches whatever URL an attribute contains is a script-injection hole the moment any attribute value comes from content an editor or visitor can influence, so list your own origin and the specific CDN host and nothing else. And when the script arrives, the element fires a script:loaded event, which your own code listens for to initialise the library on that element. Replace the placeholder host with a real one, and prefer a file you host yourself.

The figure below shows the four states of the copy button: at rest, with keyboard focus, after a successful copy, and when copying fails. The labels are the strings the script writes into the button, and the icon stays because the visible words sit in their own data-copy-label element.

Rendered output of the code above
Four copy buttons for the code WPR-LAUNCH in a two by two grid. The resting button says Copy code. The focused button has a blue focus ring. The third says Copied on a green background. The fourth says Press Ctrl+C to copy on an amber background.
A plain HTML and CSS render of the four label states of the copy-to-clipboard button, with the labels the script writes, not a screenshot of the Bricks editor.

A data-attribute toggle, and when Interactions already do the job

The eighth pattern is the most reusable of all: a state stored in a data attribute, flipped by a small script, and styled by CSS. Accordion panels, filter drawers, “show more” blocks and mobile menus are all this one idea. Keeping the state in an attribute rather than in a class has two advantages. The attribute is easy to read from both CSS and JavaScript, and it sits naturally beside the ARIA attributes that tell assistive technology what is going on.

Before writing any script, look at what Bricks already offers. The Interactions feature includes Set attribute, Remove attribute and Toggle attribute actions that work on a target element, on the element itself or on every element matching a CSS selector. If the attribute key is class, Bricks changes the class list; otherwise it sets or removes the attribute directly. A click interaction that toggles an attribute such as data-open on a target is often all you need, it needs no code at all, and it is maintained by Bricks. Write your own script only when you need something the interaction does not do, such as keeping aria-expanded on the button in step with the panel, or grouping toggles by the card they sit in.

Here is the custom version. The button carries data-toggle with a selector for its panel, plus aria-expanded set to false and aria-controls if you want to be thorough. The panel has the class named in the selector. Both live inside a wrapper that carries data-toggle-group, which keeps the lookup local, so the toggle works in query loops where IDs repeat.

document.addEventListener('click', function (event) {
  var trigger = event.target.closest('[data-toggle]');
  if (!trigger) { return; }

  var scope = trigger.closest('[data-toggle-group]') || document;
  var panel;
  try {
    panel = scope.querySelector(trigger.getAttribute('data-toggle'));
  } catch (e) {
    return;
  }
  if (!panel) { return; }

  var open = panel.getAttribute('data-open') !== 'true';
  panel.setAttribute('data-open', String(open));
  trigger.setAttribute('aria-expanded', String(open));
});

The handler finds the clicked trigger, then looks for the panel inside the nearest group, or in the whole document if there is no group. The try block protects against a mistyped selector in the attribute, which would otherwise throw. The new state is the opposite of the current one, written to the panel as data-open and to the trigger as aria-expanded. Because it is delegated, it needs no setup on dynamically added content. The CSS then animates the panel without a height calculation, by transitioning a grid row from zero to one fraction. Put it on the panel’s global class:

%root% {
  display: grid;
  grid-template-rows: 0fr;
  transition: grid-template-rows 220ms ease;
}

%root%[data-open="true"] {
  grid-template-rows: 1fr;
}

%root% > * {
  min-height: 0;
  overflow: hidden;
  visibility: hidden;
  transition: visibility 0s linear 220ms;
}

%root%[data-open="true"] > * {
  visibility: visible;
  transition-delay: 0s;
}

@media (prefers-reduced-motion: reduce) {
  %root%,
  %root% > * { transition: none; }
}

The panel must have exactly one child, a wrapper Div that holds the content; the > * rule styles it. When the grid row is zero fractions tall, the child’s min-height: 0 and overflow: hidden let it collapse completely. The visibility lines matter for accessibility: a collapsed panel that is merely clipped would still be reachable by the Tab key, with links and buttons that nobody can see. Setting visibility: hidden removes the content from the tab order and from screen readers, and the delayed transition keeps it visible until the closing animation ends. When the panel opens, the delay drops to zero so the content appears at once. Without any script, a visitor with JavaScript disabled would see a closed panel they cannot open, so if the content is essential, make the closed state a progressive enhancement: add the collapsing CSS only after the script has run, by setting a marker class on the group.

The figure below is drawn with the grid-row CSS from this section. The markup carries the attribute values the script would have set: data-open="true" on the open panel, data-open="false" on the closed ones, and a matching aria-expanded on each button.

Rendered output of the code above
Three stacked accordion items. The first and third are closed and show only their question and a downward chevron. The middle item is open, with its chevron turned upward and a short answer visible below its question.
A plain HTML and CSS render of the data-attribute toggle with one panel open and two closed, using the grid-row technique from this section, not a screenshot of the Bricks editor.

Debug custom code in the browser, step by step

Most custom code that “does not work” fails for one of five reasons: it never reached the page, it reached the page but its selector matches nothing, it matches but loses the cascade, the script threw an error, or an old copy is cached somewhere. The browser developer tools can separate these in a couple of minutes, and the order below is designed so that each step rules something out.

First, test on the front end. The Bricks Interactions documentation states that interactions run on the front end, not inside the builder canvas, and the page settings documentation gives the same advice for things such as scroll snap. Open the published page or the preview in a normal browser tab, not the builder, and keep an incognito window handy to avoid cached files and logged-in differences.

Second, confirm the code arrived. View the page source and search for a unique comment you put at the top of the snippet, or for a distinctive property value. For CSS in the page settings or global fields, Bricks prints it inline in the head, so it should be easy to find. If you changed the CSS loading method to external files, the generated files live in the uploads folder, and the Bricks documentation tells you to use the Regenerate CSS files button after switching methods; if the external files method produces missing or wrong styles, the documented fallback is to go back to inline styles. Also purge any page cache or CDN cache that sits in front of the site, since a cached page is a frozen copy of the old markup.

Third, inspect the element. Right-click it, choose Inspect, and look at the Styles pane. Your rule should be listed under the element, with its selector as Bricks wrote it. If the rule is missing, the selector does not match: compare it with the actual attributes on the element, and remember the loop caveat about IDs. If the rule is there but struck through, something else won. The pane shows the winner just below, along with the layer name in front of rules that live in a cascade layer, which is how you confirm that a Bricks default sits in the bricks layer. The Computed pane lists the final value of every property and, when you expand one, which rule supplied it.

Fourth, read the console. A red error with a file and line is a gift: Cannot read properties of null almost always means the script ran before its element existed or on a page that does not contain it, which is fixed by the ready helper and an early guard. Selecting an element in the Elements panel makes it available in the console through the dollar-zero shortcut variable, so you can test a selector by typing document.querySelectorAll('[data-copy]') and counting the results, and you can try a call by hand before wiring it to an event.

Fifth, check the network. Does the script file appear in the Network panel, with status 200 rather than 404, and is it the version you expect? For events, the Sources panel has event listener breakpoints for clicks, and you can log the Bricks events with a throwaway listener, such as document.addEventListener('bricks/ajax/nodes_added', console.log), to see when they fire. If a Code element runs executable PHP and you suspect an error, the Bricks documentation notes that adding the URL parameter brx_code_errors reveals errors that the Suppress PHP errors option hides. Finally, emulate the conditions you styled for: the Rendering panel can emulate reduced motion, and the device toolbar can emulate narrow widths for your container queries.

A fixed order for debugging custom code

  1. Test on the front endNot in the builder canvas; use a clean window.
  2. Confirm it arrivedSearch the page source; purge caches; regenerate CSS files.
  3. Inspect the elementDoes the selector exist and match the markup?
  4. Read the Styles paneStruck through? See which rule or layer won.
  5. Check the consoleErrors, null elements, wrong timing.
  6. Check the networkStatus 200, right file, right version.
Work through these steps in sequence; each one rules out a different class of problem.

Symptoms and causes: what usually goes wrong

After enough custom code, the same handful of problems keep returning. This section lists them by what you see, because that is how you meet them. Use it as a first guess, then confirm with the steps in the previous section.

The CSS works in the builder but not on the live page. The most common cause is a cached copy: a page cache plugin, a server cache or a CDN is serving markup and styles from before your change. The second is the CSS loading method. With external files, changed CSS needs the regenerate step. The third is that the builder canvas and the front end do not always render the same markup, so a selector written against what you saw in the canvas can miss on the live page. Always write against what the inspector shows on the live page.

The rule is listed but crossed out. Something with higher specificity, or the same specificity and later position, set the same property. Look at what the Styles pane says is winning. If it is the element’s own ID-level style, remove that property from the style controls or move your rule to the same place. If it is a Theme Style or a global class, check whether your selector is simply lighter than theirs. Resist the urge to reach for !important before you know which rule you are fighting; it solves today’s problem and creates next month’s.

The selector never matches. Either the placeholder was used where it is not defined, or the element lives inside a loop. The Bricks documentation describes %root% for the element and class CSS controls; outside those fields, write an ordinary selector. For loops, remember that elements inside a query loop do not get their automatic ID on the front end unless you set one, so match them by class.

The script works on load but not after Load more, filters or a popup. The listener was bound to elements that were later replaced or that did not exist yet. Switch to delegation on the document, or re-run an idempotent init function from the documented Bricks events. If your script needs to know which loop changed, the event detail provides the query ID.

The page settings have no script fields. Bricks shows those fields only to users who are allowed to add unfiltered HTML, and others see an informational notice. That is a permissions question, not a bug. Decide whether this user should be able to ship JavaScript to your site before you change anything.

The sticky element does nothing, or the smooth scroll feels broken. For sticky, look for an ancestor with an overflow value other than visible, and make sure the sticky element is not stretched to the full height of its parent. For anchor jumps, check that the target has a CSS ID, that the ID is unique, and that the scroll-padding value is at least as tall as the fixed header. A fixed header that changes height on scroll needs the custom property updated by a script or a value that covers both sizes.

Finally, a class of problem that looks like CSS but is not: two things styling the same property from two places. The Bricks notes on CSS Sync document that when the same property is set in both a style control and in custom CSS, the custom CSS wins. If a visual control in the builder seems dead, search the element’s custom CSS, its class, the page settings and the Theme Style for the same property. Decide where each property lives, and write that decision down in the snippet comment.

Symptom, probable cause, first check

Probable causeFirst check
Works in builder, not liveCache or unregenerated CSS filesPurge caches, regenerate, view live source
Rule crossed outHigher specificity or later ruleStyles pane shows the winner and its layer
Selector matches nothingWrong field for the placeholder, or loop itemCompare selector with live markup
Fails after Load moreListener bound to replaced nodesSwitch to delegation or Bricks AJAX events
Sticky does nothingAncestor overflow or stretched itemComputed overflow up the tree
No script fieldsUser cannot add unfiltered HTMLCheck the role and capabilities
A quick lookup for the problems that recur most often with custom code in Bricks.

Safety and performance: who can ship code, and what it costs

Custom code is the part of a Bricks site where the safety model changes, and it pays to understand exactly how. Bricks protects executable PHP with layers: a global code execution switch under the custom code settings, a per-role or per-user execution capability, and a signature that Bricks stores with the code and checks every time it runs. Change the code after signing and Bricks refuses to run it until it is signed again. These protections apply to the Code element’s PHP and HTML field, SVG code, query editor code and a few other executable locations.

The documentation draws a careful line that matters for this tutorial: direct CSS and JavaScript in the Code element are rendered as CSS and JS output, and the signature gate applies to the executable PHP/HTML field and the other listed locations. In plain terms, signatures protect PHP, not your stylesheets and scripts. The guard for JavaScript is a different one: the page settings script fields appear only for users who may add unfiltered HTML, and the same reasoning should guide who can edit the global custom code and the Code element. A script on your site can read forms, change links and send data elsewhere. Treat the ability to add JavaScript as an administrator-level power, grant it deliberately, and review which roles have it when a freelancer or a client editor joins.

Several habits keep scripts from becoming a liability. Never put secrets in JavaScript, data attributes or custom CSS; everything that reaches the browser is public. When you load a library from a CDN, pin an exact version, and consider the integrity and crossorigin attributes so that a tampered file is refused. Keep third-party hosts in an allow list, as in the loader above. If your site sends a Content Security Policy header, inline scripts from the page fields may be blocked unless they carry a nonce or you move them into files, which is another reason to graduate larger scripts to the child theme.

On the performance side, most of the savings come from decisions already covered. Scope code so pages receive only what they use. Defer scripts and load heavy libraries lazily. Prefer CSS to JavaScript wherever CSS can do the job: hover states, sticky positioning, line clamping, aspect ratios and smooth scrolling all cost no script at all. Use IntersectionObserver in place of scroll listeners, and mark scroll or touch listeners passive when you must use them. Animate transform and opacity rather than layout properties such as width or top. Keep selectors short, since a deep descendant chain is harder to read and gains nothing.

The Bricks asset loading article also explains that Bricks loads many frontend assets only when needed and lets you enqueue its individual libraries by handle if a third-party element needs them. That is the right model for your own assets too. If you rely on a Bricks library such as the lightbox or slider, enqueue it by its documented handle rather than loading your own copy, and test the page after any Bricks update. Finally, treat snippets as maintained code: begin each with a comment stating its purpose, its scope and the date you last reviewed it, keep anything over a screenful in a file under version control, and test changes on a staging copy before they reach production.

Checklist

  • Decide the scope of every snippet before writing it (one element or class, one page or template, several pages, or the whole site) and use the narrowest location that works.
  • Write element and class CSS against the %root% placeholder instead of a copied element ID or a hand-typed class name.
  • Set each property in one place only: either a style control or custom CSS, never both on the same element.
  • Open the browser Styles pane to confirm which rule wins before adding selectors or !important.
  • Give every hover effect a keyboard equivalent with :focus-within or :focus-visible, and add a prefers-reduced-motion override.
  • Put an aspect-ratio on image and video wrappers so the layout does not jump while media loads.
  • For container queries, give the container an explicit width and put the layout rules on its descendants, not on the container itself.
  • For a sticky sidebar, set align-self: flex-start, offset the top by the header height and check ancestors for overflow other than visible.
  • Give anchor targets unique CSS IDs and set scroll-padding-top on the html element so fixed headers do not cover them.
  • Load JavaScript only where needed: a page script field, a Code element, or a conditional enqueue with the defer strategy, plus an early guard that exits when the target is absent.
  • Write plain JavaScript with no jQuery dependency, using querySelectorAll, closest, dataset, fetch and delegated event listeners.
  • Use event delegation for clicks, and make per-element setup idempotent and re-run it on the bricks/ajax/nodes_added event.
  • Allow-list the hosts a lazy loader may fetch from, pin CDN versions, and keep secrets out of scripts, attributes and custom CSS.
  • Test on the front end in a clean browser window, with page caches purged and CSS files regenerated if you use external files.
  • Test every snippet inside a query loop, after Load more or a filter, with a popup, with the keyboard only, and at narrow widths.
  • Limit who can add JavaScript to trusted roles, begin each snippet with a comment naming its purpose, scope and review date, and test on staging before production.

About this guide. This is general guidance written by WPresident Editorial from documentation and widely used practice. WPresident has not benchmarked the products or methods described. Interfaces and plan limits change, so check the vendor’s current documentation before you act. Not legal, tax or financial advice. See our editorial policy.

Frequently asked questions

Where do I put custom CSS for a single element in Bricks?

Select the element, open the Style tab and expand the CSS control group, then write your rules there using the %root% placeholder. Bricks converts the placeholder to the element's selector, or to the class selector if you are editing a global class. This keeps the CSS attached to the element, so it travels with it when you copy it and disappears when you delete it. Use page settings for CSS that belongs to one page or template, and global custom CSS only for rules that apply everywhere.

What does %root% do, and why not just use the element ID?

The placeholder is replaced by Bricks at output time with the selector of the element or class you are editing. Element IDs are generated, so one you copy from the inspector can change meaning when the element is duplicated or moved, and elements inside query loops may not carry an automatic ID on the front end. Writing against the placeholder means the same snippet works when pasted onto another element. After saving, check the printed CSS once to confirm the selector matches your markup.

Should I use global custom CSS or page-level custom CSS?

Choose the narrowest location that reaches everything the code must affect. Page settings, in the Custom Code group, apply the CSS only to that page or template, and with the default loading method it is printed inline only there. Global custom CSS is output on every page, so every rule in it is paid for on every view. Use the global field for true site-wide rules such as the smooth-scroll offset, and use classes for reusable components.

Why does my custom CSS not override a Bricks style?

Check three things in the browser Styles pane. First, whether the winning rule sets the same property on the element's ID, which is more specific than a class. Second, whether a Theme Style or global class uses a heavier selector than yours. Third, whether the winning declaration uses !important. Bricks places its own default styles in a cascade layer, so ordinary unlayered CSS normally beats them without extra weight, but the layer does not help against element-level, class or Theme Style rules that are not in it.

Do I need !important in Bricks custom CSS?

Rarely. Because default Bricks styles live in a cascade layer and unlayered rules beat layered ones, you can usually override a default with a plain, low-specificity selector. Reserve !important for beating inline styles or third-party CSS you cannot edit. The Bricks documentation notes a special case: a default rule inside the layer that itself uses !important flips the order, and a dedicated sub-layer named bricks.reset exists for answering it. Find out what you are fighting first.

Can I use jQuery in Bricks custom JavaScript?

You can if a library or plugin on your site loads it, but you should not depend on it. Plain JavaScript covers the usual needs: querySelectorAll to select, classList for classes, closest to walk up the tree, dataset for data attributes, fetch for requests and one delegated addEventListener for events. Code without a library dependency works regardless of what other plugins load, defer or remove, and it avoids a download your page may otherwise not need.

How do I run my script again after Load more, infinite scroll or filters?

Prefer event delegation: attach one click listener to the document and check the target, which keeps working for new elements. When elements need per-item setup, write an init function that skips elements it has already processed, call it on DOM ready, and call it again from the documented Bricks events. The bricks/ajax/nodes_added event fires after new AJAX result nodes are added, and its detail includes the query ID. Popups use bricks/ajax/popup/loaded.

Does my custom JavaScript run inside the Bricks builder?

Do not rely on it. The Bricks documentation says interactions run on the front end rather than in the builder canvas, and recommends testing timing and selectors in preview or on the published page. Treat the front end as the reference environment for scripts. If you enqueue files from a child theme, the Bricks child theme guide shows a check against bricks_is_builder_main() that keeps your files out of the builder panel while still loading them in the canvas and on the site.

Are custom CSS and JavaScript protected by Bricks code signatures?

No. Code signatures cover executable code locations such as the Code element's PHP and HTML field, SVG code and query editor code. The Bricks documentation states that direct CSS and JavaScript in the Code element are rendered as output, and the signature gate applies to the executable fields. The protection for scripts is permission based: the page script fields only appear for users who can add unfiltered HTML. Decide carefully which roles hold that capability.

Should JavaScript go in the Code element, page settings or a child theme file?

Use a page settings script field or the Code element for short code tied to one page or component. Use a file in the child theme or a small site plugin, enqueued with a condition and the defer strategy, for anything larger, shared across pages or worth keeping under version control. The file route gives you browser caching, code review and easy rollback. Whichever you pick, start the script with a guard that exits when its target element is missing.

Do container queries work in Bricks?

Yes, because they are plain CSS. Mark a wrapper with container-type: inline-size, give it an explicit width, and write the component's layout inside an @container rule that targets its descendants. Bricks breakpoints respond to the viewport, so use them for page-level decisions and container queries for components that must adapt to the space they are given. After saving, view the page source once to confirm that %root% was replaced inside the at-rule too.

W
Written byWPresident EditorialThe WPresident editorial team. Every article says whether it comes from hands-on use or from documentation, and anything paid for is labelled.

Keep reading

Get the Monthly Launch Report

One email a month: the best of last month's articles, new reviews and what changed in WordPress, without the noise.

No spam. Unsubscribe in one click.

Signed and sealed,
The WPresident
↑↓ move↵ openEsc closeAll results