Size an Element on Load and Resize in WordPress

Some layout values can’t be done with CSS alone and have to be measured in the browser: when the page loads and again whenever the window is resized. A common case on WordPress sites is a decorative element that starts at the left edge of the window and ends exactly at the right edge of the centred content box.

This snippet shows the pattern for running JavaScript on load and resize, without jQuery, using that example. It measures the container once on load and again on resize, and sets the width of the target element to reach from the left edge of the window to the right edge of the container.

The snippet

(function () {
	// ===== Config =====
	var CONTAINER = '.dpc-container'; // The centred box the element lines up with.
	var TARGET = '.dpc-to-left-edge'; // The element(s) that should reach the left edge of the window.
	// ===== End of config =====

	var container = document.querySelector(CONTAINER);
	var targets = document.querySelectorAll(TARGET);
	if (!container || !targets.length) {
		return;
	}

	var frame = 0;

	function update() {
		frame = 0;
		// Distance from the left edge of the window to the right edge of the container.
		var width = Math.round(container.getBoundingClientRect().right);
		targets.forEach(function (el) {
			el.style.width = width + 'px';
		});
	}

	// Run at most once per frame, however many resize events arrive.
	function schedule() {
		if (!frame) {
			frame = window.requestAnimationFrame(update);
		}
	}

	update(); // On load.
	window.addEventListener('resize', schedule);

	// Also when the container changes size without a window resize (fonts, sidebar, accordion).
	if ('ResizeObserver' in window) {
		new ResizeObserver(schedule).observe(container);
	}
})();

Add the class dpc-container to the centred box and dpc-to-left-edge to the element that should stretch. In the block editor that is Advanced → Additional CSS class(es).

Add it with Scripts Organizer

In Scripts Organizer go to Code Blocks → Add New and give the block a name. Set Trigger location to Conditions and set Template to All, or narrow it to the pages that need the script. Under Script location tick Footer, set Footer Mode to Javascript, paste the code into the footer editor and publish.

Scripts Organizer prints header and footer code on the front end only with the Conditions trigger, not with Everywhere, and it adds the <script> tag itself, so paste the code without one.

How it works

  • update() runs once as soon as the script loads. It is printed in the footer, so the elements already exist.
  • getBoundingClientRect().right is the distance from the left edge of the window to the right edge of the container. That is the width the element needs.
  • A resize fires many events per second. schedule() uses requestAnimationFrame(), so update() runs at most once per frame.
  • ResizeObserver also calls it when the container changes size on its own, for example after web fonts load or a sidebar opens.
  • The older version used jQuery, which block themes do not load on the front end, and Oxygen element IDs.

Customise it

  • Other measurements: put your own code in update(). Keep the schedule() and listener part as it is; it is the reusable bit.
  • Several independent elements: run the snippet once per pair, or loop over containers with querySelectorAll().

Variant: CSS only

When the element sits directly inside a centred container, CSS can do the same without JavaScript:

/* The element sits directly inside a centred container. */
.dpc-to-left-edge {
	width: calc(50vw + 50%);
	margin-left: calc(50% - 50vw);
}

100vw includes the vertical scrollbar on Windows, so this version can be a few pixels too wide there; the JavaScript version measures the real position. For a similar layout see Resize image from inside container to the one edge of the page.

Gotchas

  • Width changes made by the script cause a layout shift on load. Give the element a sensible width in CSS first so the jump is small.
  • On narrow screens the container is usually full width, so the element simply gets the full width too.

In the Scripts Organizer library Import it with one click from Scripts Organizer.

// newsletter

Three tested WordPress snippets a week

Blocks, security, performance, Tailwind, PHP and React. Copy, paste, ship. You’ll also get DPlugins product updates. No spam, and you can unsubscribe anytime.

// newsletter

Three tested WordPress snippets a week

Blocks, security, performance, Tailwind, PHP and React. Copy, paste, ship. You'll also get DPlugins product updates. No spam, and you can unsubscribe anytime.