Perform a Colour Swap using JQuery

Want to perform a quick, temporary, colour change on a website? Maybe you want to see what you blog theme would look like with a different colourway but don’t want to edit line after line of CSS?

Here’s a cheeky little block of JQuery that can do just that by seeking out every element that has a particular colour, or background colour, set and replacing that colour with something else.

When you get the colour of an element in JQuery it comes back in rgb format, but you can set it using rgb, hex, or just a good old fashioned colour name. Don’t forget to tweak the color if you’re changing the background colour.

Script to change all colours using JQuery

<script>
jQuery(document).ready(function(){
	console.log("Changing colours");
	jQuery("*").each(function(){
		if(jQuery(this).css('color') == 'rgb(255, 221, 34)'){
			jQuery(this).css('color','#1C4C8D');
		}
		if(jQuery(this).css('background-color') == 'rgb(255, 221, 34)'){
			jQuery(this).css('background-color','#1C4C8D');
			jQuery(this).css('color','white');
		}
		if(jQuery(this).css('background') == 'rgb(255, 221, 34)'){
			jQuery(this).css('background','#1C4C8D');
			jQuery(this).css('color','white');
		}
		if(jQuery(this).css('border-color') == 'rgb(255, 221, 34)'){
			jQuery(this).css('border-color','#1C4C8D');
		}
	});
});
</script>

How does this script to change all colours work?

The script is pretty simple – first it gets every element on the page using the JQuery global selector “*”. Then, it simply loops through all of these looking for the offending colour and changing it.

This is not a fast option and certainly not the best way to do this – if you want to make the colour change permanent then you should update your CSS. However, for trying out global colour changes on a site where the colour codes are in multiple places in the CSS, it’s a quick and easy way to see how your site would look with a different colour.

Leave a Reply

Your email address will not be published. Required fields are marked *