JavaScript Review
- JS in HTML. Including JavaScript in HTML with
script
element, with eithersrc
attribute or JS code.
or<script src="scripts/site.js" ></script>
<script> /* JS code here */ console.log('hello from JS!'); </script>
- Variables. Declare variables with
let
and sometimesconst
.
Though you will see the oldervar
, but avoid that.
You may also seeconst
which declares a constant (a variable that won't be changed).let courseName = 'CSCI E-12', courseTerm = 'Fall 2021', courseInstructor = 'David' ;
- Console is your friend. Your browser developer tools will be critical to use, and
especially the "Console". Log to the console in JS with
console.log('hello there!');
- When is the code executed?
script
inhead
or right before the body close tag.
But it is good practice to rely on specific events, especially theDOMContentLoaded
event!The
.addEventListener
method takes two arguments. The first is the event name as a string, and the second is the function to execute when that event happens.window.addEventListener('DOMContentLoaded', function(){ /* here's where JS goes for when DOM is loaded */ console.log('the DOM has been loaded and parsed!'); });
- Events -
load
(andDOMContentLoaded
),click
,focus
,blur
,submit
,mouseover
,mouseout
,keypress
.
HTML attributes are available, but don't use these. Add event listeners through JavaScript! - Functions. Functions can be named, and they can also be anonymous (unnamed) when setting event handlers. Functions can have arguements.
Named function that accepts an argument:
function square(x) { let numberSquared = x*x; return numberSquared; }
Anonymous functions —
function() {}
— are often used in setting event listenerswindow.addEventListener('DOMContentLoaded', function(){ /* here's where JS goes for when DOM is loaded */ console.log('the DOM has been loaded and parsed!'); });
- DOM Methods can be used to access the DOM as well as manipulate it! Some common DOM methods are
getElementById
,getElementsByTagName
,createElement
,createTextNode
,appendChild
, and there are others!