24. Styling Your Content


In This Chapter

Learn how to change CSS using JavaScript

Understand the pros and cons of setting styles directly as opposed to adjusting class values

Use classList to make fiddling with element class values a breeze


In the previous chapter, we looked at how to modify your DOM’s content using JavaScript. The other part of what makes our HTML elements stand out is their appearance, their styling. When it comes to styling stuff, the most common way is by creating a style rule and have its selector target an element or elements. A style rule would look as follows:

.batman {
    width: 100px;
    height: 100px;
    background-color: #333;
}

An element that would be affected by this style rule could look like this:

<div class="batman"></div>

On any given web page, you’ll see anything from just a few to many MANY style rules each beautifully stepping over each other to style everything that you see. This isn’t the only approach you can use to style content using CSS, though. It wouldn’t be HTML if there weren’t multiple ways to accomplish the same task!

Ignoring inline styles, the other approach that you can use to introduce elements to the goodness that is CSS that revolves around the DOM and JavaScript. Basically, you can use JavaScript to directly style an element, and you can also use JavaScript to add or remove class values on elements which will alter which style rules get applied. In this chapter, you’re going to learn about both of these approaches.

Onwards!

Why Would You Set Styles Using JavaScript?

Before we go further, it is probably useful to explain why you would ever want to use JavaScript to affect the style of an element in the first place. In the common cases where you use style rules or inline styles to affect how an element looks, the styling kicks in when the page is loaded. That’s awesome, and that’s probably what you want most of the time.

There are many cases, especially as your content gets more interactive, where you want styles to dynamically kick in based on user input, some code having run in the background, and more. In these sorts of scenarios, the CSS model involving style rules or inline styles won’t help you. While pseudoselectors like hover provide some support, you are still greatly limited in what you can do.

The solution you will need to employ for all of them is one that involves JavaScript. JavaScript not only lets you style the element you are interacting with, but more importantly, it allows you to style elements all over the page. This freedom is very powerful and goes well beyond CSS’s limited ability to style content inside (or very close to) itself.

A Tale of Two Styling Approaches

Like I mentioned in the introduction, you have two ways to alter the style of an element using JavaScript. One way is by setting a CSS property directly on the element. The other way is by adding or removing class values from an element which may result in certain style rules getting applied or ignored. Let’s look at both of these cases in greater detail.

Setting the Style Directly

Every HTML element that you access via JavaScript has a style object. This object allows you to specify a CSS property and set its value. For example, this is what setting the background color of an HTML element whose id value is superman looks like:

var myElement = document.querySelector("#superman");
myElement.style.backgroundColor = "#D93600";

To affect many elements, you can do something as follows:

var myElements = document.querySelectorAll(".bar");

for (var i = 0; i < myElements.length; i++) {
    myElements[i].style.opacity = 0;
}

In a nutshell, to style elements directly using JavaScript, the first step is to access the element. I am using the querySelector function to make that happen. The second step is just to find the CSS property you care about and give it a value. Remember, many values in CSS are actually strings. Also remember that many values require a unit of measurement like px or em or something like that to actually get recognized.

Adding and Removing Classes Using classList

A common way to style elements is by adding and removing class values on their class attribute. Let’s say we have the following div element:

<div id="myDiv" class="bar foo zorb"> ... </div>

From looking at the markup, we can see that this element has a class attribute with the bar, foo, and zorb values set. What we are going to do in this section is see how easy it is to manipulate these class values using the classList API. This API is great because it is simple and provides the following methods to manipulate class values:

• add

• remove

• toggle

• contains

What these four methods do may be pretty self-explanatory from their names, but let’s look at them in further detail anyway. Gotta get the page count up somehow, right?

Adding Class Values

To add a class value to an element, call the add method on classList:

var divElement = document.querySelector("#myDiv");
divElement.classList.add("baz");


alert(divElement.classList);

After this code runs, our div element will have the following class values: bar, foo, zorb, baz. The classList API takes care of ensuring that spaces are added between class values and all the other sort of stuff that CSS expects from your HTML content.

If you specify an invalid class value, the classList API will throw an exception and not add it. If you tell the add method to add a class that already exists on the element, your code will run without exception (ha!) but the duplicate class value will not get added.

Removing Class Values

To remove a class value, just call the remove method on classList:

var divElement = document.querySelector("#myDiv");
divElement.classList.remove("foo");


alert(divElement.classList);

After this code executes, the foo class value will be removed. What you will be left with is just bar and zorb. Pretty simple, right?

Toggling Class Values

For many styling scenarios, there is one very common workflow. First, you check if a class value on an element exists. If the value exists, you remove it from the element. If the value does not exist, you add that class value to the element. To simplify this very common toggling pattern, the classList API provides you with the toggle method:

var divElement = document.querySelector("#myDiv");
divElement.classList.toggle("foo"); // remove foo
divElement.classList.toggle("foo"); // add foo
divElement.classList.toggle("foo"); // remove foo


alert(divElement.classList);

The toggle method, as its name implies, adds or removes the specified class value on the element each time it is called. In our case, the foo class is removed the first time the toggle method is called. The second time, the foo class is added. The third time, the foo class is removed. You get the picture.

Checking Whether a Class Value Exists

The last thing we are going to look at is the contains method:

var divElement = document.querySelector("#myDiv");

if (divElement.classList.contains("bar") == true) {

    // do something
}

This method checks to see if the specified class value exists on the element. If the value exists, you get true. If the value doesn’t exist, you get false.

Going Further

As you can see, the classList API provides you with almost everything you need to add, remove, or inspect class values on an element very easily. The emphasis being on the word almost. For the few things the API doesn’t provide by default, you can go online and read my full article on everything that you can do with classList: http://bit.ly/kClassList.


Image Tip

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.171.51