CSS, Styling, and Dimensions

Contact Us or call 1-877-932-8228
CSS, Styling, and Dimensions

CSS, Styling, and Dimensions

jQuery includes a handy way to get and set CSS properties of elements.

Note

CSS properties that normally include a hyphen need to be camel cased in JavaScript. For example, the CSS property font-size is expressed as fontSize in JavaScript.

Getting CSS Properties

$('h1').css('fontSize'); // returns a string such as "19px"

Setting CSS Properties

// setting an individual property
$('h1').css('fontSize', '100px');

// setting multiple properties
$('h1').css({ 'fontSize' : '100px', 'color' : 'red' });

Note the style of the argument we use on the second line -- it is an object that contains multiple properties. This is a common way to pass multiple arguments to a function, and many jQuery setter methods accept objects to set multiple values at once.

Using CSS Classes for Styling

As a getter, the $.fn.css method is valuable; however, it should generally be avoided as a setter in production-ready code, because you don't want presentational information in your JavaScript. Instead, write CSS rules for classes that describe the various visual states, and then simply change the class on the element you want to affect.

Working With Classes

var $h1 = $('h1');

$h1.addClass('big');
$h1.removeClass('big');
$h1.toggleClass('big');

if ($h1.hasClass('big')) { ... }

Classes can also be useful for storing state information about an element, such as indicating that an element is selected.

Dimensions

jQuery offers a variety of methods for obtaining and modifying dimension and position information about an element.

The code in the example below is just a very brief overview of the dimensions functionality in jQuery; for complete details about jQuery dimension methods, visit http://api.jquery.com/category/dimensions/.

Basic Dimensions Methods

Code Sample:

jqy-concepts/Demos/basic-dimensions.html
---- C O D E   O M I T T E D ----
$(document).ready(function() {
	var msg = "";
	// set the width of all H1 elements
	$('h1').width('300px');
	
	// gets the width of the first H1
	msg += "Width: " + $('h1').width() + ", ";
					
	// sets the height of all H1 elements
	$('h1').height('150px');
	
	// gets the height of the first H1
	msg += "Height: " + $('h1').height() + "\n";
	
	// returns an object containing position
	// information for the first H1 relative to
	// its "offset (positioned) parent"
	msg += 
		"Top: " + $('h1').position().top + ", " +
		"Left: " + $('h1').position().left;
	alert(msg);
});

---- C O D E   O M I T T E D ----
</html>

Attributes

An element's attributes can contain useful information for your application, so it's important to be able to get and set them.

The $.fn.attr method acts as both a getter and a setter. As with the $.fn.css method, $.fn.attr as a setter can accept either a key and a value, or an object containing one or more key/value pairs.

Getting Attributes

// returns the href for the first a element in the document
	$('a').attr('href');

Setting Attributes

Manipulating a Single Attribute

The attr method will change an attribute or property of a selection.

$('#myDiv a:first').attr('href', 'newDestination.html');

Manipulating Multiple Attributes

The attr method can accept an object instead of two separate parameters -- all of the object's properties will be used to set corresponding properties in the selection.

$('#myDiv a:first').attr({
	href : 'newDestination.html',
	rel : 'super-special'
}).html('New Destination');

Manipulating Attributes Using a Function

You can also specify a function for an attribute's value -- the function will be invoked for each element in the collection. It can examine the tag and calculate a value from the tag'a properties.

$('#myDiv a:last').attr({
	rel : 'super-special',
	href : function() {
		return 'new/' + $(this).attr('href');
	}
}.html('new/Destination'));

Code Sample:

jqy-concepts/Demos/setting-attributes.html
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
<script>
$(document).ready(function() {
	$('a').attr({ 
			'title' : 'all titles are the same too!', 
			'href' : 'allMyHrefsAreTheSameNow.html' 
	});
	$('a:first').attr('href', 'somethingNew.html');
});
</script>
</head>
<body>
<a href="#">Home</a>
<a href="#">Top</a>
<a href="#">Up</a>
</body>
</html>

This time, we broke the object up into multiple lines. Remember, whitespace doesn't matter in JavaScript, so you should feel free to use it liberally to make your code more legible! You can use a minification tool later to strip out unnecessary whitespace for production.

Using a Function to Determine an Attribute's New Value

Code Sample:

jqy-concepts/Demos/change-attributes.html
---- C O D E   O M I T T E D ----
<script>
$(document).ready(function() {
	// Manipulating single attributes
	$('#myDiv a:first').attr('href', 'newDestination.html');
	
	// Manipulating multiple attributes
	$('#myDiv a:first').attr({
		href : 'newDestination.html',
		rel : 'super-special'
	}).html('New Destination');
	
	// Manipulating attributes using a function
	$('#myDiv a:last').attr({
		rel : 'super-special',
		href : function() { 
			return 'new/' + $(this).attr('href');
		}
	}).html('new/Destination');

	// just to verify that the rel attribute got set
	$('#myDiv [rel=super-special]').addClass("redText");
});
</script>
</head>
<body>
<div id="myDiv">
	<a target="popup" href="#">Old destination (here).</a>
	<a target="popup" href="#">Old destination (here).</a>
	<a target="popup" href="#">Old destination (here).</a>
</div>
</body>
</html>


Removing Attributes

jQuery provides $.fn.removeAttr(attributeName) for this purpose.

Showing and Hiding Elements

While these will be covered in more detail later, the show() and hide() methods do what you might expect -- show or hide the selected elements.

Iterating Over a Selection

If you have a complex task to perform on your selection, you can iterate over its elements using $.fn.each. The function that you pass to this method is run individually for all of the elements in a selection. The function receives the index of the current element and the DOM element itself as arguments. Inside the function, the DOM element is also available as this. (The DOM element is not a jQuery object, though -- it is a plain JavaScript element.)

Code Sample:

jqy-concepts/Demos/selection-iterating.html
<html>
<head>
<script src="../../jqy-libs/jquery.js"></script> 
<script src="../../jqy-libs/fix-console.js"></script> 
<script>
$(document).ready(function() {
	$('#myList li').each(function(idx, el) {
		console.log(
			'Element ' + idx + 
			' has the following html: ' +
			$(el).html()
		);
	});
});
</script>
</head>
<body>
<ul id="myList">
	<li>A</li>
	<li class="selected">B</li>
	<li>C</li>
	<li>D</li>
	<li>E</li>
</ul>
</body>
</html>
Next