CIS 115 - Linking CSS and Using JavaScript

Objectives

  • Link a CSS file to a web page
  • Link a JavaScript file to a web page
  • Create a JavaScript function that runs when a web page loads
  • Create a JavaScript file that modifies a web page

Linking CSS to a web page

You can take the CSS rules that are contained within the "style" element of your web page and save them to a separate text file with a .css extension. You can then link them to the web page using a "link" element. For example, if the "head" element of your web page looks like this:

<head> <title>Title of page</title> <meta charset="utf-8"> <style> .blue { background-color: blue; } p { text-indent: 3em; } </style> </head>

You can remove the CSS rules to a separate file. Let's name it rules.css. It would contain the following:

.blue { background-color: blue; } p { text-indent: 3em; }

You would then change the "head" element of your web page to the following:

<head> <title>Title of page</title> <meta charset="utf-8"> <link rel="stylesheet" href="rules.css"> </head>

Linking JavaScript to a web page

Just like the CSS above was linked to a web page, you can also link JavaScript program code to a web page. Linking JavaScript uses the "script" element instead of the "link" element. If the JavaScript is contained in a file named code.js, then the "head" element could be modified as follows to add the JavaScript code:

<head> <title>Title of page</title> <meta charset="utf-8"> <link rel="stylesheet" href="rules.css"> <script src="code.js"></script> </head>

Making JavaScript run when the page loads

JavaScript can not safely act on a web page until after it has loaded (unless the web page is being created by JavaScript). A common technique for doing this is the following:

window.onload = function() { // the JavaScript code would go here };

That tells the browser to wait to run the code within the function until the browser sends the signal that the page has finished loading. Note that a linked JavaScript file contains only JavaScript code - not HTML. Likewise, a linked CSS file contains only CSS rules and not HTML.

Changing the content of an element using JavaScript

You can easily modify elements that have an id using JavaScript. To change the content of an element with the (HTML) id of "greeting" to be the text "Hello world!", use the following code:

document.getElementById("greeting").innerHTML = "Hello, world!";

You can also easily modify CSS style settings using JavaScript. To change the background color of an element with the (HTML) id of "greeting" to #00ff00, use the following code:

document.getElementById("greeting").style.backgroundColor = "#00ff00";