===
Module leader:
General queries and admin issues:
Graeme Stuart: gstuart@dmu.ac.uk
===
Reminders
- make separate GitHub repos for re-usable lab code
- make one thing work and test it
- Decide how to use JavaScript in your project
- check the browser console (f12/cmd-alt-i) for errors
- always validate your HTML as you develop!
===
There is a predefined document object in JavaScript, which can be used to access all elements in the DOM.
This document object is the root of all objects in your webpage.
To access HTML elements, start with the document object, e.g.:
document.body.innerHTML = "Some text";(body is an element of the DOM, so you access it with the document object, then you can change the content of its innerHTML property)
A more scalable example:
function addTextNode() {
const myheading = document.createElement("h1");
const mytext = document.createTextNode("Hello Big Heading!");
myheading.appendChild(mytext);
document.body.appendChild(myheading);
}You can get a reference to elements by tag, id, class:
document.getElementsByTagName("section"); // returns a list
document.getElementById("my_id"); // no '#' needed && returns single item
document.getElementsByClassName("my_class"); // no '.' needed & returns a listW3Schools: JavaScript HTML DOM Elements
document.querySelectorAll uses CSS-style selectors:
document.querySelector("p#id"); // returns one item
document.querySelectorAll("p.intro"); // returns a list
document.querySelectorAll("main section:first-child"); // returns a list
document.querySelectorAll('.mydata [data-period="current"]'); // returns a list===
The simplest possible example (in HTML/JS files):
<p id="my-id">Click me!</p>// store a reference to the element to be clicked:
const clickThing = document.getElementById("my-id");
// what to do when the user clicks:
function do_stuff() {
alert("You clicked me!");
}
// or you can use the simpler "fat arrow" syntax:
const do_stuff = () => { alert("You clicked me!"); }
// "listen" for the click:
clickThing.addEventListener("click", do_stuff);Get the date and display it (HTML/JS):
<button id="myBtn">What's the date?</button>
<p id="demo">I've no idea. Click the button.</p>document.getElementById("myBtn").addEventListener("click", showDate);
const dateDemo = document.getElementById("demo");
function showDate() {
let d = new Date();
dateDemo.innerHTML = `Oh, it’s: ${d.toDateString()}!`;
}- DEMO: Show date
- W3Schools: JavaScript HTML DOM EventListener
- W3Schools: JavaScript toDateString() Method
get a name from a form and display it (HTML/JS):
<form id="getName" action="#" method="post">
<label for="userName">Enter name:</label>
<input id="userName" type="text" placeholder="name here please :-)">
<input type="submit">
</form>
<p>Hello, <span id="myName">anonymous user! Your name?</span></p>function PerformGreeting() {
if(userName.value){
myName.innerHTML = `<strong>${userName.value}</strong>!`;
} else {
myName.innerHTML = `<strong>person with no name</strong>!`;
}
event.preventDefault(); // disables default form submission
}
getName.addEventListener("submit", PerformGreeting);You can also manipulate CSS with JavaScript…
<p>A link <a class="thelinks" href="#">link 1 text</a>.</p>
<p>Another link <a class="thelinks" href="#">link 2 text</a>.</p>
<button id="changeLinks">Change link colours</button>.changeMe {
background: #336; color: #fcc; transition: all 1s;
}const thelinks = document.getElementsByClassName('thelinks');
const addClass = () => {
for(i in thelinks){
thelinks[i].classList.toggle("changeMe");
}
}
changeLinks.addEventListener("click", addClass);You can also change CSS with JavaScript… e.g. a background image:
<p>See a: <span id="car">Tesla</span> / <span id="cat">kitten</span>!</p>
<p id="picture">your choice of picture here</p>function showImage() {
picture.innerHTML = "";
console.log(event.target.id);
picture.classList = event.target.id;
}
[car,cat].forEach(c => c.addEventListener( "click", showImage ));DEMO: swap CSS class
…and the CSS for styling, and the fade transition:
#picture {
font-size: 75%;
text-align: center;
line-height: 178px;
height: 178px;
width: 300px;
background-repeat: no-repeat;
border: solid #999 2px;
transition: all 1s;
}
.car {
background-image: url("images/tesla-model-s.jpg");
}
.cat {
background-image: url("images/kitten.jpg");
}===
A JavaScript object contains name:value pairs inside curly braces {}
It can contain nested objects
IMPORTANT: no comma after the last items!
Here, the range object is a child of the car object:
const car = {
manufacturer: "Tesla",
model: "Model S",
range: { normal: "360", ludicrous: "200" },
colour: "red",
query: function(){
answer.innerHTML =
`The <strong>${car.manufacturer} ${car.model}</strong> has a \
<strong>${car.range.normal} mile</strong> normal range.`;
}
};
question.addEventListener("click", car.query);
car.range.ludicrous; // returns: 200Here’s the HTML:
<p id="question">How far will the Tesla travel if you don’t drive like a maniac?</p>
<p id="answer"></p>- DEMO: Accessing object properties
- DEMO: Traversing items in a nested object
- MDN: Working with Objects
An array of objects is a common JSON data format used for exchanging data on the web e.g. from APIs
const animals = [
{ cat: {
horns: "none",
fluff: "loads",
eyes: "super-advanced, research this"
}
},
{ goat: {
horns: "yes",
fluff: "not really",
eyes: "really weird, you should check"
}
}
];
animals[0].cat.horns // "none"===
Please discuss module-related issues and questions with your module tutor or module leader
