HTML/CSS/JS - Intro Session 3
01 Sep 2015As we continue covering the basic concepts of front-end web development, the main focus this week will be JavaScript.
This is where we left off our HTML and CSS files, more or less:
index.html
style.css
A very important HTML attribute to know about, and use, is id.
The id attribute lets us give a unique identifier to any HTML element on our web page.
The class attribute is very similar but for a group of HTML elements.
The id and class attributes are useful because they allow us to refer to specific HTML element or element(s) from our CSS and from our JavaScript.
So, finally, let’s talk some JavaScript
As we did in the case of CSS, we need to let our HTML document know about our JavaScript code.
Note:
- can be placed in either <head> or <body> sections
- rule of thumb:
- 3rd party libraries in <head> section
- custom JavaScript in <body> section
- e.g. just before </body> to ensure elements referenced have been rendered
Variables:
Here’s how a variable is defined in JavaScript.
Note:
- the keyword var
- variable assignment operator
- naming rules and conventions
- letters, numbers, _ , $
- cannot start with a number
- meaningful
- camel-case
- case-sensitive
- common simple types: numeric, string, boolean
Built-in functions:
alert() is a built-in JavaScript function.
- display values of variables and expressions
- crude but useful tool for a quick check/test
Another built-in JavaScript function is getElementById()
- fetches an HTML element from our page so we can do something to it, e.g. to style it dynamically
Note:
- dot notation as in document. and style.fontSize
Programmer-defined functions:
Note the difference between defining a function and executing it.
The above defines a function, but to actually call it we need to add:
Functions can also be called via …
Event Listeners:
In JavaScript we can watch for particular events and react to them.
- to watch out (“listen”) for particular UI event (e.g. click) on particular element (e.g. button)
- to execute some code (e.g. handler function) whenever that event occurs
The above two lines of JavaScript code
- get the button element from the HTML document and save it to a variable
- tells the browser to execute myFunction when the button is clicked
As an exercise, let’s add to our example web page the facility to:
- choose a colour from a drop-down and
- set the text of our paragraph to be displayed in that colour.
Suggested steps:
- make sure each element has a unique id
- get the button element
- add an event listener so that button click would call a function
- create the function
- get the selected colour
- get the paragraph element
- apply the colour to the paragraph element
Sample solution:
index.html
script.js
No changes to style.css were required at all.