11 min read

Inline CSS modification

Before we jump into the nifty jQuery effects, a quick look at CSS is in order. One way of modifying a document’s appearance is by defining styles for classes in a separate stylesheet and then adding or removing those classes with jQuery. Typically, this is the preferred process for injecting CSS into HTML because it respects the stylesheet’s role in dealing with the presentation of a page. However, there may be times when we need to apply styles that haven’t been, or can’t easily be, defined in a stylesheet. Fortunately, jQuery offers the .css() method for such occasions.

This method acts as both a getter and a setter. To get the value of a style property, we simply pass the name of the property as a string, like .css(‘backgroundColor’). Multi-word properties can be interpreted by jQuery when hyphenated, as they are in CSS notation (background-color), or camel-cased, as they are in DOM notation (backgroundColor). For setting style properties, the .css() method comes in two flavors—one that takes a single style property and its value and one that takes a map of property-value pairs:

.css('property','value')
.css({property1: 'value1', 'property-2': 'value2'})

Experienced JavaScript developers will recognize these jQuery maps as JavaScript object literals.

Numeric values do not take quotation marks while string values do. However, when using the map notation, quotation marks are not required for property names if they are written in camel-cased DOM notation.

We use the .css() method the same way as using .addClass() —by chaining it to a selector and binding it to an event. To demonstrate this, we’ll use the style switcher example.

<div id="switcher">
<div class="label">Text Size</div>
<button id="switcher-default">Default</button>
<button id="switcher-large">Bigger</button>
<button id="switcher-small">Smaller</button>
</div>
<div class="speech">
<p>Fourscore and seven years ago our fathers brought forth
on this continent a new nation, conceived in liberty,
and dedicated to the proposition that all men are created
equal.</p>
</div>

By linking to a stylesheet with a few basic style rules, the page can initially look like the following screenshot:

In this version of the style switcher, we’re using <button> elements. Clicking on the Bigger and Smaller buttons will increase or decrease the text size of <div class=”speech”>, while clicking on the Default button will reset <div class=”speech”> to its original text size.

If all we wanted were to change the font size a single time to a predetermined value, we could still use the .addClass() method. But let’s suppose that now we want the text to continue increasing or decreasing incrementally each time the respective button is clicked. Although it might be possible to define a separate class for each click and iterate through them, a more straightforward approach would be to compute the new text size each time by getting the current size and increasing it by a set factor (for example, 40%).

Our code will start with the $(document).ready() and $(‘#switcher-large’).click() event handlers:

$(document).ready(function() {
$('#switcher-large').click(function() {
});
});

Next, the font size can be easily discovered by using the .css() method: $(‘div.speech’).css(‘fontSize’). However, because the returned value will include a trailing ‘px‘, we’ll need to strip that part in order to perform calculations with the value. Also, when we plan to use a jQuery object more than once, it’s generally a good idea to cache the selector by storing the resulting jQuery object in a variable as well.

$(document).ready(function() {
var $speech = $('div.speech');
$('#switcher-large').click(function() {
var num = parseFloat($speech.css('fontSize'), 10);
});
});

The first line inside $(document).ready() now stores a variable for <div class=”speech”> itself. Notice the use of a $ in the variable name, $speech. Since $ is a legal character in JavaScript variables, we can use it as a reminder that the variable is storing a jQuery object.

Inside the .click() handler, we use parseFloat() to get the font size property’s number only. The parseFloat() function looks at a string from left to right until it encounters a non-numeric character. The string of digits is converted into a floating-point (decimal) number. For example, it would convert the string ‘12′ to the number 12. In addition, it strips non-numeric trailing characters from the string, so ’12px’ becomes 12 as well. If the string begins with a non-numeric character, parseFloat() returns NaN, which stands for Not a Number. The second argument for parseFloat() allows us to ensure that the number is interpreted as base-10 instead of octal or some other representation.

All that’s left to do, if we are increasing by 40%, is to multiply num by 1.4 and then set the font size by concatenating num and ‘px’:

$(document).ready(function() {
var $speech = $('div.speech');
$('#switcher-large').click(function() {
var num = parseFloat($speech.css('fontSize'), 10 );
num *= 1.4;
$speech.css('fontSize', num + 'px');
});
});

The equation num *= 1.4 is shorthand for num = num * 1.4. We can use the same type of shorthand for the other basic mathematical operations, as well: addition, num += 1.4; subtraction, num -= 1.4; division, num /= 1.4; and modulus (division remainder), num %= 1.4.

Now when a user clicks on the Bigger button, the text becomes larger. Another click, and the text becomes larger still, as shown in the following screenshot:

To get the Smaller button to decrease the font size, we will divide rather than multiply —num /= 1.4. Better still, we’ll combine the two into a single .click() handler on all <button> elements within <div id=”switcher”>. Then, after finding the numeric value, we can either multiply or divide depending on the ID of the button that was clicked. Here is what that code looks like now:

$(document).ready(function() {
var $speech = $('div.speech');
$('#switcher button').click(function() {
var num = parseFloat( $speech.css('fontSize'), 10 );
if (this.id == 'switcher-large') {
num *= 1.4;
} else if (this.id == 'switcher-small') {
num /= 1.4;
}
$speech.css('fontSize', num + 'px);
});
});

We can access the id property of the DOM element referred to by this, which appears here inside the if and else if statements. Here, it is more efficient to use this than to create a jQuery object just to test the value of a property.

It’s also nice to have a way to return the font size to its initial value. To allow the user to do so, we can simply store the font size in a variable immediately when the DOM is ready. We can then use this value whenever the Default button is clicked. To handle this click, we could add another else if statement. However, perhaps a switch statement would be more appropriate.

$(document).ready(function() {
var $speech = $('div.speech');
var defaultSize = $speech.css('fontSize');
$('#switcher button').click(function() {
var num = parseFloat( $speech.css('fontSize'), 10 );
switch (this.id) {
case 'switcher-large':
num *= 1.4;
break;
case 'switcher-small':
num /= 1.4;
break;
default:
num = parseFloat(defaultSize, 10);
}
$speech.css('fontSize', num + 'px');
});
});

Here we’re still checking the value of this.id and changing the font size based on it, but if its value is neither ‘switcher-large’ nor ‘switcher-small’ it will default to the initial font size.

Basic hide and show

The basic .hide() and .show() methods, without any parameters, can be thought of as smart shorthand methods for .css(‘display’,’string’), where ‘string’ is the appropriate display value. The effect, as might be expected, is that the matched set of elements will be immediately hidden or shown, with no animation.

The .hide() method sets the inline style attribute of the matched set of elements to display:none. The smart part here is that it remembers the value of the display property—typically block or inline—before it was changed to none. Conversely, the .show() method restores the matched set of elements to whatever visible display property they had before display:none was applied.

For more information about the display property and how its values are visually represented in a web page, visit the Mozilla Developer Center at https://developer.mozilla.org/en/CSS/display/ and view examples at https://developer.mozilla.org/samples/cssref/display.html.

This feature of .show() and .hide() is especially helpful when hiding elements whose default display property is overridden in a stylesheet. For example, the <li> element has the property display:block by default, but we might want to change it to display:inline for a horizontal menu. Fortunately, using the .show() method on a hidden element such as one of these <li> tags would not merely reset it to its default display:block, because that would put the <li> on its own line. Instead, the element is restored to its previous display:inline state, thus preserving the horizontal design.

A quick demonstration of these two methods can be set up by adding a second paragraph and a “read more” link after the first paragraph in the example HTML:

<div id="switcher">
<div class="label">Text Size</div>
<button id="switcher-default">Default</button>
<button id="switcher-large">Bigger</button>
<button id="switcher-small">Smaller</button>
</div>
<div class="speech">
<p>Fourscore and seven years ago our fathers brought forth
on this continent a new nation, conceived in liberty,
and dedicated to the proposition that all men are
created equal.
</p>
<p>Now we are engaged in a great civil war, testing whether
that nation, or any nation so conceived and so dedicated,
can long endure. We are met on a great battlefield of
that war. We have come to dedicate a portion of that
field as a final resting-place for those who here gave
their lives that the nation might live. It is altogether
fitting and proper that we should do this. But, in a
larger sense, we cannot dedicate, we cannot consecrate,
we cannot hallow, this ground.
</p>
<a href="#" class="more">read more</a>
</div>

When the DOM is ready, the second paragraph is hidden:

$(document).ready(function() {
$('p:eq(1)').hide();
});

And the speech looks like the following screenshot:

Then, when the user clicks on read more at the end of the first paragraph, that link is hidden and the second paragraph is shown:

$(document).ready(function() {
$('p:eq(1)').hide();
$('a.more').click(function() {
$('p:eq(1)').show();
$(this).hide();
return false;
});
});

Note the use of return false to keep the link from activating its default action. Now the speech looks like this:

The .hide() and .show() methods are quick and useful, but they aren’t very flashy. To add some flair, we can give them a speed.

Effects and speed

When we include a speed (or, more precisely, a duration) with .show() or .hide(), it becomes animated—occurring over a specified period of time. The .hide(‘speed’) method, for example, decreases an element’s height, width, and opacity simultaneously until all three reach zero, at which point the CSS rule display:none is applied. The .show(‘speed’) method will increase the element’s height from top to bottom, width from left to right, and opacity from 0 to 1 until its contents are completely visible.

Speeding in

With any jQuery effect, we can use one of three preset speeds: ‘slow’, ‘normal’, and ‘fast’. Using .show(‘slow’) makes the show effect complete in .6 seconds, .show(‘normal’) in .4 seconds, and .show(‘fast’) in .2 seconds. For even greater precision we can specify a number of milliseconds, for example .show(850). Unlike the speed names, the numbers are not wrapped in quotation marks.

Let’s include a speed in our example when showing the second paragraph of Lincoln’s Gettysburg Address:

$(document).ready(function() {
$('p:eq(1)').hide();
$('a.more').click(function() {
$('p:eq(1)').show('slow');
$(this).hide();
return false;
});
});

When we capture the paragraph’s appearance at roughly halfway through the effect, we see something like the following:

Fading in and fading out

While the animated .show() and .hide() methods are certainly flashy, they may at times be too much of a good thing. Fortunately, jQuery offers a couple other pre-built animations for a more subtle effect. For example, to have the whole paragraph appear just by gradually increasing the opacity, we can use .fadeIn(‘slow’) instead:

$(document).ready(function() {
$('p:eq(1)').hide();
$('a.more').click(function() {
$('p:eq(1)').fadeIn('slow');
$(this).hide();
return false;
});
});

This time when we capture the paragraph’s appearance halfway, it’s seen as:

The difference here is that the .fadeIn() effect starts by setting the dimensions of the paragraph so that the contents can simply fade into it. To gradually decrease the opacity we can use .fadeOut().

LEAVE A REPLY

Please enter your comment!
Please enter your name here