Goals
One of the real thrills of JavaScript is that you can dynamically manipulate CSS. In this lesson we will learn about how to operate CSS from JavaScript. We will also learn about accessing properties of HTML elements.
- Understand the relationship between CSS and JavaScript style objects.
- Understand that from property names of CSS, property names of JavaScript style objects can be generated.
- Understand how to change the style appropriately from JavaScript.
- Understand how to access element properties appropriately from JavaScript.
CSS
CSS syntax and selector syntax
In CSS, we decorate documents by listing styles. The designation of each style basically takes the form of “where” and “what to do”.
Selectors
It is the selector that designates “where”. There are various ways to specify where in the HTML document (to which element) the style is applied, but the easiest thing is to write the HTML element name as it is.
For example, if you write “h1”, style is applied to heading 1, we refer to it as the h1 element.There are various kinds of methods for specifying CSS selectors. The main ones are summarized in the following table.
SYNTAX | Explanation |
---|---|
* { color:red; } | Adapt style to all elements to turn red |
div { color:red; } | Change the style of a specific block or div to turn red |
div* { color:red; } | Change the style of all the elements within the div to red |
div#hoge { color:red; } | Change style to div element of id name hoge to red |
div.fuga { color:red; } | Change the style of all div elements of the class name fuga |
h1, h2 { color:red; } | Change the style of all Heading 1 and Heading 2 elements to red |
div#hoge p { color:red; } | Change the style of all p elements within the div of class name hoge |
div:hover { color:red; } | Change the color of the div when the user’s hovers over it |
a:link { color:red; } | [Pseudo class] Change style of a link element that has not been visited |
a:visited { color:red; } | [Pseudo class] Change style of a visited link elements |
Since there are various other designation methods, we cannot go into all the details. If you wish to learn more, we encourage you to look into it and experiment on your own.
Declaration (Property and Value)
In CSS, after specifying “where”, enclose it in {} and describe “what to do”. This is called a style declaration. The declaration is a set of properties and values, and it is described in the form of “○ ○: ××”. Here, ○○ is a property, and xx is a value set for that property. For example, writing “color: blue” means “Set text color to blue”.
If there are multiple declarations, separate them with a semicolon. However, in the case where there is only one declaration, it is OK to add one “; (semicolon)” at the end. Therefore, after the declaration there is less trouble if you get into the habit of attaching a semicolon.
CSS Box Model
There are box models and things that are useful to know when decorating with CSS. One must imagine that every element is surrounded by a transparent box.
Let’s consider p element as an example. In the following figures, the vertical and horizontal width, the frame line, the outer margin, and the inner margin are designated by the CSS.
Let’s assume that the character string “transparent box structure” enclosed in p elements is in a transparent box. First, let’s assume that the size of the box is 30px by 100px in width and 100px in width, with a red border and a solid line with a thickness of 5px. Here, the boundary line of the transparent box is known as the frame line.
The margin is between this frame line and the inside. The inner margin or padding is all the way up to the character. The outer region between the inner margin and the boundary of the box is simply referred to as the margin.
In other words, when considering the box model, it is structured as follows:
outer margin> frame line> inner margin> content (letters, images, etc.).
Types of decoration
If you use CSS well, you can make a lot of elegant web application designs. First of all, let us look at basic decorative examples. In this case, color designation when changing character color and background color is done using color codes.
Change the background color (Element with the ID bar1)
p#bar1{ background: #ff1493; }
Example
Shocking Pink
Change the text color (Element with the ID bar2)
CSS
p#bar2{ color: #ff0000; }
Example:
Has the color changed?
Styling fonts
CSS
p#bar3{ font-weight: bold; } p#bar4{ font-weight: lighter; } p#bar5{ font-style: italic; }
Example
Bold
Normal
Itallic
Decorating Text
Text Position
Adding a border
CSS
p#hoge13 { border: 3px #000 solid; }
Example
Border: 3px thickness, black
Specify margins (with border and color for comparison)
Margin adjustment (With border and color comparison)
CSS
p#hoge14 { margin: 10px; } p#hoge15 { padding: 10px; }
Example
Margin:10px
Padding:10px
New decoration styles
Currently we mainly use a version of CSS called CSS 3 (CSS Level 3). In CSS 3, it is possible to specify finer decorations such as gradation, transparent color, 2D & 3D transformation and animation.
Newly added (adopted) functions in CSS 3 can not be used unless they have already been implemented in the browser being used. Specifications of each function of CSS are standardized at the end of a long formulation process. However, rather than being implemented in the browser after being standardized, the functions to be adopted are preliminarily implemented in each browser.
In many cases, the update is repeated in accordance with a formulated specification. Therefore, when new functions are adopted in CSS, there are many cases where they can already be used with commonly used browsers such as Firefox, Chrome and Safari. Meanwhile, because functions implemented by browsers have not become standards in CSS, or because the specifications differed, it is sometimes impossible to decorate as expected.
Gradation
At present, the gradation function called linear-gradient () is being standardized. This can be used in situations that require specific colors. However, care must be taken because there are limitations; the color of characters cannot be changed.
CSS
p#bar16 { background: linear-gradient(white, gray); } p#bar17 { background: linear-gradient(to right, #ff0000, #fff); } p#bar18 { background: linear-gradient(45deg, red, orange, yellow, green, blue, indigo, violet); }
Example:
For circular gradation, we use radial-gradient ().
Changing the transparency
There are two ways to specify transparency. In order to change the transparency of an element, we must first designate a color, and the specify the transparency (or opacity).
To specify transparency at the same time as specifying a color, use rgba (). rgba () has a version of transparency added to rgb () and takes four arguments. The first to the third are the values of 0 to 255 red, green and blue, and the fourth argument is the transparency and takes values from 0 to 1.
CSS
p#bar19 { background-color: rgba(0, 0, 255, 0.7); }
Example
alpha=0.9
alpha=0.7
alpha=0.5
alpha=0.3
alpha=0.1
To specify transparency without using rgba(), use opacity. Opacity can be used as a property. Values range from 0 to 1, so you need to be careful as % expressions can not be used here.
CSS
p#bar20 { background-color: #00ff00; opacity: 0.7 /* Opacity at 70% */; }
Examples
0.9
0.7
0.5
0.3
0.1
Animation
CSS also allows for some basic animation for transitions, movements and effects.
CSS
div#bar21 { animation-name: anime1; animation-duration: 5s; animation-iteration-count: 10; } @keyframes anime1 { 0% {width: 50px; height: 50px; background-color: aqua;} 70% {width: 500px; height: 50px; background-color: blue;} 100% {width: 50px; height: 50px; background-color: aqua;} }
Example
Property | Explanation |
---|---|
animation-name | Set the animation name |
animation-duration | Determine how long the animation should continue |
animation-iteration-count | Determine how many times the animation should repeat |
animation-delay | Determine how much delay there should be in the animation |
Referencing from CSS and JavaScript
As you have seen, you can decorate the web pages in many ways by using CSS. This also includes decorations with movements like animation. However, the decoration with movements mentioned here can only perform predetermined operation, and they do not change their movement dynamically depending on user’s interactions. We will now learn how to dynamically change the CSS of a page by using JavaScript.
Retrieving Elements
First, let’s undersatand the relationship between JavaScript programs and CSS. In CSS, various elements are decorated by specifying elements to be decorated using a selector and then setting properties for it. JavaScript is essentially the same; it acquires an element and manipulates the properties for that element thereafter.
You can use getElementById (), getElementsByClassName (), getElementsByTagName (), to retrieve the element in JavaScript. Elements can also be acquired with childNodes [] and firstChild of the DOM.
An example of obtaining actual elements is shown below. In all examples, the variable ele contains an element.
Accessing the style
After getting HTML elements with JavaScript, you can access the CSS directly by referring to the element’s style property. For example, if an element is stored in the variable ele, you can access CSS by using ele.style. More specifically, when accessing a color, since the property name of CSS is color, it becomes ele.style.color. However, it is not possible to use the property name including “- (minus sign)” as it is (it is recognized as subtraction in JavaScript), it is necessary to delete the “-” and capitalize the next letter. For example, in the case of the background color (background-color) of the element stored in ele, it is ele.style.backgroundColor.
CSS | JavaScript |
---|---|
color | color |
display | display |
background-color | backgroundColor |
text-size | textSize |
text-align | textAlign |
CSS operations with JavaScript
In the previous section we learned how to refer to CSS from JavaScript. We will now learn to actually operate CSS from JavaScript. One can dynamically change styles by assigning values using JavaScript reference. See the example below.
HTML
The color here should change <button onclick="changeStyle();">Click Me</button>
CSS
#p1234 {color: red;}
JavaScript
var size = 12; var color = "red"; function changeStyle() { size = size + 1; if (color == "red" { color = "black"; } else { color = "red"; } var ele = document.getElementById("p1234"); ele.style.fontSize = size + "px"; ele.style.color = color; }
The color here should change.
In this example, when the button is pressed, the changeColor () function is called. In the changeColor () function, the value of the variable size is incremented by 1 at the beginning.
In the next if statement, the value is set to “black” when the value of the variable color is “red”, and “red” in the case of “black”. Then, using element style, we set it as font size and character color, respectively.
Note: “px” is required as a unit for the font size.
Exercise 6-
As shown below, write a program so that when you click on a sentence the line will be struck out or removed.
Clicking here will cause the strikethrough to be invoked or cause the line to disappear.
Exercise 6-
When there is HTML like the following, create a button to change the background color of elements including ccc, aaa and bbb to the color input in the input area. However, when you press the second button, return to the initial state.
Element 1 Element 2 Element 3 Element 4 Element 5
Element 1
Element 2
Element 3
Element 4
Element 5
Exercise 6-
Create a program that behaves like a tab as below.
Hint 1: The HTML section is as follows.
<div class="tabbox"> <div class="tabs"> <a class="tab1" onclick="ChangeTab1();">タブ1</a> <a class="tab2" onclick="ChangeTab2();">タブ2</a> <a class="tab3" onclick="ChangeTab3();">タブ3</a> </div> <div id="tab1" class="tab tab1"> これはタブ1です。 </div> <div id="tab2" class="tab tab2"> これはタブ2です。 </div> <div id="tab3" class="tab tab3"> これはタブ3です。 </div> </div>
ヒント2: スタイルでdisplayプロパティをnoneにするとその要素が表示されなくなる。displayプロパティをblockにすると表示される。