A little bit of color

Even though we generally don't use CSS in any of our examples, we will look a little bit at CSS in this. By no means is this going to give you everything you need about CSS, but it will give you some idea of the power of CSS.

Intro to CSS

CSS stands for Cascading Style Sheets. The most important part of that acronym is the C, for cascading. What this means is that the whole set of styles are applied in a layered fashion. Any attribute that is applied using a more specific selector is applied on top of the original. In addition, a style affects not only the element you specify, but all elements contained inside it. It cascades down into the document

CSS can affect everything about an html element. It can even specify different contents for the element! The following is an incomplete list of things that can be changed with CSS

Attribute affectedExample
Size of the element (width and height)hello!
Positionhello!
Color of texthello!
Color of backgroundhello!
Fonthello!
Size of fonthello!
Borders
hello!

In most cases, CSS is the preferred way to affect the appearance of HTML elements. There are other ways, and most of them are not used any more. Some still are, like bold tags

Coloring the results

If you remember in our lesson 3 code, we created a loop to repeat the text we were showing a specified number of times. What if we wanted to select a color to display the text in? In this case, we need to create some CSS styles to specify the color of the element.

Here is a sample CSS directive, which will color text blue:

p.bluetext {
    color: blue;
}

The part that says p.bluetext is called the selector. This part has a very complex and vast set of possibilities, and essentially says to the browser "all the directives inside this block are applied to anything that the selector identifies". The selector can select specific element types, or can select based on many many different types of attributes. We are not going to go over all the possibilities, as there are too many, and it involves getting into the nitty gritty of HTML design and CSS design. We are only going to talk about the ones that are the easiest to understand, classes and elements.

In the case above, we have specified an element type of p (for paragraph) and class called "bluetext". A class is a tag you can apply to any html element in the page. It works very similarly to the id attribute, but unlike the id, it does NOT have to be unique in the document. It looks like this:

<p class="bluetext">hello!</p>

Any number of classes can be applied to an element, separated by spaces, and any number of classes can be used in a selector. Each class in a selector is preceeded by a dot. Elements are always the first item in the selector. If you wanted all elements with the bluetext class, regardless of element type, you would omit the p from the selector

So for example, if we wanted to apply style to all elements with both the "bluetext" and the "goofball" classes, we would use a selector of .bluetext.goofball.

Similarly, if we wanted to affect ALL p elements in the document, regardless of class, we could simply use p as the selector.

Let's make all the text in our document blue! We can do this by applying the style to the body tag. It will apply to all text inside the body tag of the HTML document, which holds all the visible document elements. Add this to your CSS box on your page editor:

body {
    color: blue;
}

You may have to click the run button again, but now you should see all the text in your example being blue! Remember to delete this style, as we are going to do something similar with our code next, and we don't want all the document being blue.

Select element

As if all this isn't confusing enough, we have a new type of HTML element to learn -- the select element. Just like an input element creates a text box or checkbox, a select element creates a clickable drop-down.

Add the following to your html page, before the button, but after the other input elements:

<select id="color">
    <option value="">Pick Color</option>
    <option value="bluetext">Blue</option>
    <option value="redtext">Red</option>
</select>

The select element should look like this:

As you can see, the select element creates a drop down. Each of the dropdown selections is represented with an option element. The value attribute on the option tells us what value the select element will have when the user selects it. Go ahead and add this code to your javascript function, so you can see what the value of the select element is after you select something (and push the button):

var colorval = document.getElementById('color').value
alert(colorval)

hint: you should get "bluetext" or "redtext" to display in the alert when you select those options

Now, remove the alert, and let's apply the value of the item as a class to our target element. In order to set the class of a specific element using Javascript, we need to set the className property of the element:

var colorval = document.getElementById('color').value
target.className = colorval

Internally, what this is doing is telling the browser that the target element now has the class that the user selected. But this doesn't actually color the text! We still need to define a style for those classes that colors the text properly. The final step is to define the CSS to color the text (put this in your CSS box on your editor):

.bluetext {
    color: blue;
}

.redtext {
    color: red;
}

Don't forget to click the run button, now you should be able to change your repeated text to blue or red in addition to being bold!

The Complete example

Below is a complete example that you can copy and paste into a file, and then run on your browser. If you want to see this in a fiddle, see here, but try it yourself before looking at the answer!

<!DOCTYPE html>
<html>

<head>
    <title>Lesson 3 bonus!</title>
<style>
.bluetext {
    color: blue;
}
.redtext {
    color: red;
}
</style>
    <script>
        function showString() {
            var ischecked = document.getElementById('option').checked
            var str = document.getElementById("thestring").value
            var target = document.getElementById('code')
            var colorval = document.getElementById('color').value
            target.className = colorval

            var result = ""
            var count = parseInt(document.getElementById('count').value)
            while(count > 0)
            {
                result = result + str
                count = count - 1
            }
            
            if(ischecked) {
                target.innerHTML= "<b>" + result + "</b>"
            }
            else {
                target.innerHTML = result
            }
        }
    </script>
</head>

<body>
    Result appears here:
    <span id="code"></span>
    <p>
        <input id="thestring" placeholder="text">
        <input type="checkbox" id="option"> Bold
        <input type="number" id="count" value="1">
        <select id="color">
            <option value="">Pick Color</option>
            <option value="bluetext">Blue</option>
            <option value="redtext">Red</option>
        </select>
        <button type="button" onclick="showString()">Click Me</button>
    </p>
</body>

</html>

Playgrounds

As always, here are some playgrounds you can use. The JSFiddle playground links to a base project you can fork that includes the javascript console.

You can also open a local file (if you have a normal computer), name it anything with a .html extension, and then open it in your browser and it will work!

©2019 Steven Schveighoffer