Much like the previous lesson, this lesson focuses on using jQuery with webpages. Since jQuery was designed to work with webpages, it was designed to work with both HTML and CSS on those pages.
This article will focus on using jQuery with CSS on web pages.
Styling
jQuery can affect the style of an element very easily through the use of the
css
method. Since jQuery is used for styling like this,
the styles applied are applied as inline styles
rather than anything else. This means they are applied only to that element.
It is possible using the css
method to obtain the current value of a
CSS property from an element. This example will get the colour of the h1
element on the page.
//This will get the colour of the title.
alert(jQuery("h1").css("color"));
The css
method can also change the value of a property and it is fairly straightforward to use.
In order for jQuery to know that a property is to be set (rather than obtained) it takes in two parameters.
The first parameter specifies which property needs to be changed on the element(s)
and the second parameter specifies what it is to be changed to.
//This will change the colour of and add an underline to the title.
jQuery("h1").css("color", "green").css("text-decoration", "underline");
Of course, this is not ideal if multiple properties need to be changed since each
property needs to be specified in a method call. jQuery offers an alternate way of
doing this using a key-to-value pair object. To do this,
properties are written in a JSON format. That means that they are surrounded by curly braces ({}
)
and key-to-value pairs are separated by commas (,
) and specified using
colons (:
). This example does exactly the same as the previous, but uses this
object-notation instead.
//This will change the colour of and add an underline to the title.
jQuery("h1").css({"color" : "green", "text-decoration" : "underline"});