Week 4 - Changing CSS attributes
19 Mar 2010 - tips-tutorials
Welcome to week 4 of our five tutorials on JQuery for beginners.
This week I will show you how to add CSS styles to elements on a page of your website.
Adding CSS Styles
For this example, I will add a background of red to a page element when clicking on a link.
Here is an example of what we shall produce:
click to add background
How to develop it
First, attach the JQuery library as explained in lesson 1. If you have yet to view this lesson visit lesson 1 now.
Now we will produce the HTML for this example which will consist of an anchor tag and when it is clicked will add a red background to a header.
The header has been given an empty class so JQuery can add a class to the header.
For this example, we will also need to add some CSS styles to the page. To make the red background appear, we add a class to the element. This class will have the background colour set to red. The class is named 'red'.
Now for the JQuery which we will add the background colour to the header
Breaking Down The Code
This means when the document object is ready code inside the { } will be executed.
We an anchor tag with a class of 'link' is clicked, a function will be executed.
Here all elements with an ID of 'header' will have a class of red added to them. Remember, we set anything with a class of 'red' to have a background colour of red in the SS
This takes away any action the anchor tag may have so therefore it will only activate the JQuery and redirect the page.
Finished code
Your Comments
Comment on this Post
There are no comments for this post yet.