jQuery Change CSS Dynamically – It’s Easy!

Share this article

Key Takeaways

  • jQuery provides an easy way to dynamically change CSS styles on a website, using the .css() function to modify specific properties, such as color, float, background-color, and many more.
  • In addition to modifying existing CSS styles, jQuery allows for the removal of styles via the .removeClass() method, and the extension of existing styles based on their current values, such as padding or margin.
  • Multiple CSS properties can be changed simultaneously using jQuery, and it is also possible to add, remove or toggle CSS classes on elements, animate CSS properties, or change CSS properties based on their current values, user interactions like hover, click, or scroll.
change-css-with-jquery CSS Function Demo Changing your website styles dynamically is now the craze that is taking over the web! In this short, but sweet post I will explain how to do some simple yet effective CSS tricks using jQuery. This is a must know for all you avid jQuery developers!

Change Specific CSS Element

It’s really easy to change CSS with jQuery this is the format of the .CSS() function.
$('jQuery selector').css({"css property name":"css property value"});
Here are some common examples:
//change paragraph text colour to green 
$('p').css({"color":"green"});

//float all divs with class .left
$('div.left').css('float');

//change all elements with class .bg-red to have a red background
$('.bg-red').css({"background-color":"red"});

Nest Your jQuery CSS Commands

It is handy to know jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. This will not only save you alot of time but it looks prettier!
newimg.css({'background-image': 'url('+newimgsrc+')'});
newimg.css({'position': 'absolute'});
newimg.css({'height': '70px'});
newimg.css({'width': '200px'});
newimg.css({'top': '68px'});
newimg.css({'right': '2px'});
Is exactly the same as:
newimg.css({'background-image': 'url('+newimgsrc+')', 'position': 'absolute', 'height': '70px', 'width': '200px', 'top': '68px', 'right': '2px'});

Remove CSS Styles

There are two main ways to remove CSS styles not much difference between them. 1. You can remove the class associated with the page or element
//remove text color from a div
$('#mydiv').removeClass('colors');
2. You can also remove CSS styles on certain elements directly
//remove text color from a div
$('#mydiv').css('color', '');
This is also a nifty jQuery CSS trick to remove and add a class in the same call.
//change text color from red to green (classes specified in stylesheet)
$('#div').removeClass('red').addClass('green');

Extending Existing Styles Values

You may wish to just extend a style based upon it’s current value. For example, if an element’s padding-left was 10px then the following code would result in a total padding-left of 25px.
.css( "padding-left", "+=15" )

jQuery .CSS() Function Property

As most of you avid jQuery developers know, as of jQuery 1.4, .css() allows us to pass a function as the property value. This is handy for returning current CSS values to determine changes.
$('div.example').css('width', function(index) {
  return index * 50;
});

Common Background CSS Changes

Here are some examples of changing background CSS.
$('#myDiv').css('background-image', 'my_image.jpg');
// OR
$('#myDiv').css('background', 'path/to/image.jpg');
// OR
$('#myDiv').css("background-image", "url(/myimage.jpg)");  

<br /><br />
<h2>A Full Code Example - Set Div Background Image</h2>
This is a full example of jQuery Code to set a background image into a div dynamically when the page is loaded.

[code lang="js"]
<script type='text/javascript'>
$(document).ready(function() {
	//preload image (add timestamp to prevent cache)
	var newimgsrc = 'https://www.sitepoint.com/wp-content/uploads/jquery4u/2011/03/jquery-plugins2.jpg?' + (new Date().getTime());
	var newimg = $('#header');
    //replace the image
	$('#header').css("background-image", "url("+newimgsrc+")");
	newimg.css({'background-image': 'url('+newimgsrc+')', 'position': 'absolute', 'height': '70px', 'width': '200px', 'top': '68px', 'right': '2px'});
	newimg.show();
});
</script>

Frequently Asked Questions about Changing CSS with jQuery

How Can I Use jQuery to Change Multiple CSS Properties at Once?

jQuery allows you to change multiple CSS properties simultaneously using the .css() method. This method accepts an object where you can define multiple CSS properties and their new values. Here’s an example:

$("p").css({
"background-color": "yellow",
"font-size": "200%"
});
In this example, all paragraph elements will have their background color changed to yellow and their font size increased to 200%.

Can I Use jQuery to Add CSS Classes to Elements?

Yes, jQuery provides the .addClass() method which allows you to add one or more classes to selected elements. This is particularly useful when you have predefined CSS classes and you want to apply them dynamically. Here’s how you can do it:

$("p").addClass("highlight");
In this example, the “highlight” class will be added to all paragraph elements.

How Can I Remove CSS Classes from Elements Using jQuery?

jQuery provides the .removeClass() method to remove one or more classes from selected elements. Here’s an example:

$("p").removeClass("highlight");
In this example, the “highlight” class will be removed from all paragraph elements.

Can I Toggle CSS Classes on Elements Using jQuery?

Yes, jQuery provides the .toggleClass() method which allows you to add a class if it’s not already present, or remove it if it is. Here’s an example:

$("p").toggleClass("highlight");
In this example, the “highlight” class will be toggled on all paragraph elements.

How Can I Get the Current Value of a CSS Property Using jQuery?

You can use the .css() method to get the current value of a specific CSS property. You just need to pass the property name as a string. Here’s an example:

var color = $("p").css("color");
In this example, the current color of the first paragraph element will be stored in the “color” variable.

Can I Use jQuery to Change CSS Properties Based on Their Current Values?

Yes, jQuery allows you to pass a function to the .css() method. This function will be called for each selected element, and its return value will be used as the new value for the property. Here’s an example:

$("p").css("font-size", function(index, value) {
return parseFloat(value) * 1.2 + "px";
});
In this example, the font size of all paragraph elements will be increased by 20%.

Can I Use jQuery to Animate CSS Properties?

Yes, jQuery provides the .animate() method which allows you to create custom animations by changing CSS properties over time. Here’s an example:

$("p").animate({
"opacity": 0.5,
"font-size": "200%"
}, 2000);
In this example, the opacity and font size of all paragraph elements will be animated over 2 seconds.

How Can I Use jQuery to Change CSS Properties on Hover?

You can use the .hover() method in combination with .css() to change CSS properties when the mouse pointer hovers over an element. Here’s an example:

$("p").hover(function() {
$(this).css("color", "red");
}, function() {
$(this).css("color", "");
});
In this example, the color of paragraph elements will be changed to red on hover, and reset to the original color when the mouse pointer leaves.

Can I Use jQuery to Change CSS Properties on Click?

Yes, you can use the .click() method in combination with .css() to change CSS properties when an element is clicked. Here’s an example:

$("p").click(function() {
$(this).css("color", "red");
});
In this example, the color of paragraph elements will be changed to red when they are clicked.

How Can I Use jQuery to Change CSS Properties on Scroll?

You can use the .scroll() method in combination with .css() to change CSS properties when the user scrolls the page. Here’s an example:

$(window).scroll(function() {
$("p").css("color", "red");
});
In this example, the color of all paragraph elements will be changed to red when the user scrolls the page.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

gitCSjQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week