Dynamic Background Color Change for WordPress Buttons


Sohail Mumtaz

10/25/20222 min read

This tutorial demonstrates how to implement a dynamic background color change for buttons in a WordPress website using JavaScript within the Elementor builder. By following these steps, you will be able to customize the appearance of buttons by comparing their text with the page title

In this tutorial, we will utilize JavaScript to add functionality to our buttons created with Elementor. By comparing the button text with the page title, we can dynamically change the background color of the button to create a visually appealing and interactive user experience.

First of all, create 4 buttons in Elementor, go to advance settings of each button and add the class "category-btns". You can use your own class.

Drag and drop the "HTML" widget onto the desired section of your page layout. Once you have added the HTML element, you can paste the provided code inside it. Click on the added HTML element in the Elementor editor. In the left sidebar, you will see the settings for the HTML element. Look for the text area labeled "HTML Code" or similar. Paste the following code into the text area.


jQuery(document).ready(function($) {

var pageTitle = document.title.trim();

var pageWords = pageTitle.split(' ');


var pageName = pageWords.join(' ');

//console.log('Page Name:', pageName);

var buttons = $('.category-btns .elementor-button');

buttons.each(function() {

var buttonText = $(this).text().trim();

if (buttonText === pageName) {

$(this).css('background-color', '#FE4800');

$(this).css('color', 'white');





The first part of the code retrieves the current page title and assigns it to the variable pageTitle. document.title returns the title of the page, and .trim() removes any leading or trailing whitespace from the title. In wordpress post category page, pageTitle returns the title in this format: Page_name Archive Website_name. That's why we use .split(' ') So that we can split the title into words and use splite('-3') to remove the last 3 words Archive and website_name. The line pageWords.splice(-3); removes the last three elements (words) from the pageWords array. This effectively removes the last three words from the page title.


The provided code is specifically designed for a post category page created using Elementor Pro. Its purpose is to add post categories at the top of the page and dynamically change the background color of each category based on the active page.

To achieve this functionality, the code utilizes jQuery and JavaScript. It starts by retrieving the current page title and modifying it to create a shortened page name without the last three words. This modified page name is used to determine the background color for each post category button.

Related Stories