How to Add CSS Style Using jQuery Dynamically

By | November 27, 2013

With jQuery, it is possible to do some interesting CSS tricks such as changing the style of your site dynamically. Let’s say for instance you with to have a certain style applied to your site when a number of conditions are met.You can do all that in jQuery when constructing the site. In case you are a beginner or advanced jQuery developer, this is a very useful trick to learn.

There are a number of things that are involved in changing the css style of a website. The general format of the jQuery css() function is this:

Let’s take a scenario where we would like to change the text color on a page to blue, float all div elements with class .left and change the background of all elements that have the .bg-green class to have a green background. All we will be required to do is have the following bunch of code and we are good to go.

You can also nest your jQuery CSS commands in order to not only save time, but make your code look much prettier. Take a look at the following piece of code.

As you can see, the second chunk of code is much shorter and simpler to read as compared to the first one. This is due to the fact that jQuery can easily interpret the CSS formatting of multiple-word properties. Smaller chunks of code are also easier to read and debug as compared to longer ones.

Removing CSS Styles

When it comes to removing CSS styles using jQuery, there are two approaches to this. First, you can remove the class that the element or page is associated with. Alternatively you can remove the CSS styles from an element directly. In both cases, you still achieve the same result in the end so there is no much difference between them. The code snippets below show both approaches.

Removing the class linked to the element

Removing CSS styles directly

For those situations when you wish to remove and add a class at the same time, there is one clever trick that does both in the same call. This comes in very handy in some situations so it is good that you know how to use it.

In other cases, you can extend a style depending on the current existing values. For example, the following code extends the value of padding-left from its existing value to a value greater by 10 pixels.

jQuery is a very powerful tool when it comes to changing the styles on a site dynamically. You build amazing effects dynamically using jQuery.

Interesting related Links

Leave a Reply

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