How to Create Dynamic CSS Styles

If you’re looking to dynamically change your CSS styles based on the current page URL in WordPress, you’re in the right place. In this guide, we’ll walk through a step-by-step process using vanilla JavaScript and the HFCM plugin.

Setting Up

Select Head Element

To begin, we need to select the <head> element where we’ll be inserting our dynamically created styles. To accomplish this, we can use the following JavaScript:

const head = document.querySelector(“head”);

Create Style Element Dynamically

Next, let’s create a <style> tag using JavaScript dynamically:

const styleElement = document.createElement(‘style’);

Append Style Tag to Head

Now, we’ll append our newly created <style> tag to the <head> element:

head.append(styleElement);

Creating Page Objects

We’ll define a JavaScript function for creating page objects, each with three properties: URL, color, and rgba.

function Page(url, color, rgba) {
this.url = url;
this.color = color;
this.rgba = rgba;
}
Now, let’s create page objects for different pages on our website:
const about = new Page(“https://beanstalkweb.com/about/”, “–about”, “–aboutRGBA”);
const gallery = new Page(“https://beanstalkweb.com/gallery/”, “–gallery”, “–galleryRGBA”);
const contact = new Page(“https://beanstalkweb.com/contact/”, “–contact”, “–contactRGBA”);
const faq = new Page(“https://beanstalkweb.com/frequently-asked-questions/”, “–faq”, “–faqRGBA”);
const home = new Page(“https://beanstalkweb.com/”, “–home”, “–homeRGBA”);

Iterating Over Pages

Now, let’s create an array of these page objects:

const pages = [home, about, gallery, contact, faq];

Now, we can then iterate over these pages and dynamically generate CSS based on the current URL:

for (const page of pages) {
const currentUrl = window.location.href;

if (currentUrl === page.url) {
// Dynamically create CSS based on the current page
const links = document.createTextNode(`a , a.phone-link {color: var(${page.color});}`);
const hamburger = document.createTextNode(`.mobile_menu_bar:before, .mobile_menu_bar:after, .et_toggle_slide_menu:after {color: var(${page.color});}`);
const formButton = document.createTextNode(`#gform_1 input[type=submit] { border-color: var(${page.color}); background-color: var(${page.color});}`);
const sideMenu = document.createTextNode(`.et_slide_in_menu_container, #top-header {background-color: var(${page.color});}`);

// Array of styles
const styles = [links, hamburger, formButton, sideMenu];

// Append styles to the dynamically created <style> tag
for (const style of styles) {
styleElement.appendChild(style);
}
}
}

And that’s it! You’ve successfully created dynamic CSS styles that change based on the current page URL using vanilla JavaScript and the HFCM plugin in WordPress. Feel free to customize the colors and styles to match your website’s design.

After reading what you’ve read, do you have any additional questions about WordPress? Contact Beanstalk and let’s chat.