Javascript#
Required Video: CS50W - Lecture 5 - Javascript Watch this before you do the reading.
JavaScript, often abbreviated as JS, is a high-level, interpreted programming language. It’s one of the three core technologies of the World Wide Web, alongside HTML and CSS. While HTML provides the structure and CSS adds style, JavaScript makes web pages interactive, responding to user actions like clicks, drags, and key presses.
JavaScript’s syntax, or the set of rules that define how JavaScript programs are constructed, is relatively straightforward. You’ll work with variables, which are like containers that store data, and you’ll encounter different data types, such as numbers, strings, and booleans. JavaScript also includes a variety of operators for performing operations on these values, and control structures that dictate the flow of your code.
What is JavaScript?#
JavaScript is a high-level, interpreted scripting language. It is multi-paradigm, supporting object-oriented, imperative, and declarative programming styles (like functional programming). Although it was initially developed to enhance web browser interactions, JavaScript has grown beyond the browser. It is now used in a variety of other environments, such as server-side programming (Node.js), mobile application development (React Native, Ionic), and even in desktop application development (Electron).
What Can JavaScript Do?#
JavaScript is incredibly versatile. It was originally created to make web pages more interactive. Here are some of the tasks that JavaScript can be used for on the web:
Dynamic Content Modification: JavaScript can change the content of a web page on the fly, without needing to reload the page. This makes web pages more responsive and interactive.
Form Validation: JavaScript can validate input data before it is sent to a server. This saves server resources and leads to a better user experience.
User Interaction: JavaScript can react to user actions like clicks, mouse movements, and key presses, and execute code in response.
Animation: JavaScript can control multimedia, create images, and even animate them.
How Does JavaScript Fit into Web Development?#
JavaScript is an essential part of any web application. Here’s how it fits into the bigger picture:
HTML is used to structure the content of the web page, creating a skeleton of sorts.
CSS is then used to format this structured content, adding colors, positioning elements, setting fonts, and more.
JavaScript is the final layer. It’s like the nervous system of the web page, making it reactive to user input and enabling dynamic behavior.
Capabilities of JavaScript#
JavaScript is a powerful language that can interact with HTML and CSS to create dynamic and interactive web experiences. Let’s delve into some of the broad capabilities of JavaScript:
Changing HTML Content#
One of the most common uses of JavaScript is to change the content of an HTML document dynamically. It can manipulate the Document Object Model (DOM), which is a representation of the structure of an HTML document.
Here’s a simple example. Suppose you have a paragraph element in your HTML:
<p id="example">Hello, world!</p>
You can use JavaScript to change the content of this paragraph:
document.getElementById("example").innerHTML = "Hello, JavaScript!";
After running this JavaScript code, your HTML paragraph will now read “Hello, JavaScript!”.
Modifying CSS Styles#
JavaScript can also manipulate the styles of an HTML document. This allows you to change the look and feel of your website dynamically.
Consider an HTML element with the id “example”:
<p id="example">Hello, world!</p>
You can use JavaScript to change the CSS styles of this element. For example, you could change the color of the text and the background color:
let element = document.getElementById("example");
element.style.color = "white";
element.style.backgroundColor = "black";
After running this JavaScript code, your HTML paragraph will now have white text on a black background.
Reacting to User Events#
Another key feature of JavaScript is its ability to react to user events, such as mouse clicks, key presses, and touch events on mobile devices. This allows you to create a highly interactive user experience.
For example, you can use JavaScript to define a function that will be executed when a button is clicked:
<button id="myButton">Click me!</button>
document.getElementById("myButton").onclick = function() {
alert("Button clicked!");
};
In this example, when the user clicks the button, an alert box will pop up with the message “Button clicked!”.
DOM#
One of the most powerful features of JavaScript is its ability to manipulate the Document Object Model (DOM). The DOM represents the structure of your web pages and can be manipulated with JavaScript to change content, style, and even the structure of the page itself. Imagine being able to change any part of your web page dynamically, in response to user actions!
In JavaScript, you can respond to user actions through events. An event could be a click, a mouseover, a key press, or even the page loading. By writing JavaScript code that listens for these events, you can create interactive web pages that engage and respond to your users.
One common use of JavaScript in web development is form validation. JavaScript can check that the user has entered valid information before the form is submitted. If the data is invalid, JavaScript can display a message to the user, preventing the form from being submitted until the issues are fixed.
As we delve deeper into JavaScript, we’ll encounter AJAX, a technique for updating parts of a web page without reloading the whole page. AJAX allows you to make HTTP requests to retrieve data from a server, and then use JavaScript to process and display the data on your page.
Throughout this chapter, we’ll also emphasize best practices in JavaScript development. This includes tips for organizing your code, naming conventions, and strategies for debugging when things don’t go as planned.
By the end of this chapter, you’ll have a solid foundation in JavaScript and be ready to create interactive, dynamic web pages. So, let’s get started on this exciting journey into the world of JavaScript!
Diving into JavaScript Syntax#
Let’s start by exploring some fundamental aspects of JavaScript syntax. We’ll begin with variables. In JavaScript, we use the let
keyword to declare a variable. For example:
let greeting = "Hello, World!";
In this example, we’ve declared a variable named greeting
and assigned it the string value “Hello, World!”.
JavaScript also provides several operators that we can use to perform operations on our variables. For example, we can use the +
operator to concatenate (join together) strings:
let greeting = "Hello,";
let name = " World!";
let fullGreeting = greeting + name; // "Hello, World!"
Control structures in JavaScript, like if
statements and for
loops, allow us to control the flow of our code. Here’s an example of a simple if
statement:
let number = 10;
if (number > 5) {
console.log("The number is greater than 5.");
}
And here’s an example of a for
loop, which prints the numbers 1 through 5 to the console:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Working with the DOM#
One of the most powerful aspects of JavaScript is its ability to manipulate the Document Object Model (DOM). The DOM represents the structure of your web pages. With JavaScript, you can select, add, modify, and delete DOM elements.
Here’s an example of how to select an element by its ID and change its text content:
document.getElementById("myElement").textContent = "New text!";
And here’s how you can change the style of an element:
document.getElementById("myElement").style.color = "red";
You can also create new elements and add them to the DOM. Here’s how to create a new paragraph element and add it to the body of the page:
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
document.body.appendChild(newParagraph);
Listening for Events#
JavaScript allows you to make your web pages interactive by listening for user events like clicks, mouse movements, and key presses. Here’s an example of how to make a button show an alert when it’s clicked:
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
In this example, we’re using the addEventListener
method to attach a “click” event listener to the button. When the button is clicked, the function we’ve provided will be called, and the alert will be shown.
Ensuring DOM Readiness: The DOMContentLoaded Event#
In front-end JavaScript development, we often need to attach event handlers to elements in the Document Object Model (DOM). However, a common issue arises when our JavaScript code, loaded in the <head>
of an HTML document, attempts to interact with DOM elements before they have been fully loaded and parsed by the browser. This results in methods like document.querySelector(...)
returning null
, as there are no elements to find yet.
Consider the following example:
function handleClick(event) {
// handles a click event
};
const elem = document.querySelector("#myelement");
elem.addEventListener('click', handleClick);
In this code, we’re trying to attach a click event handler to an element with the id “myelement”. But if this code is executed before the DOM is fully loaded, document.querySelector("#myelement")
will return null
, and we’ll get a TypeError when we try to call addEventListener
on null
.
To solve this issue, we need to ensure that our code doesn’t try to interact with DOM elements until after the DOM has fully loaded. Fortunately, JavaScript provides an event just for this purpose: the DOMContentLoaded
event. This event fires after the browser has finished loading and parsing the body of the page, populating the DOM.
We can attach a function to the DOMContentLoaded
event, and put our DOM-interacting code inside this function. Here’s how we can modify the previous example to use the DOMContentLoaded
event:
// A function for attaching events to DOM elements
function setupEvents() {
const elem = document.querySelector("#myelement");
elem.addEventListener('click', handleClick);
};
// Attach our setup function to DOMContentLoaded
document.addEventListener('DOMContentLoaded', setupEvents);
Now, our setupEvents
function won’t be called until after the DOM has finished loading, ensuring that document.querySelector("#myelement")
will find the element we’re looking for.
A Simple JavaScript Example#
Let’s dive into a simple JavaScript example that changes the color of an HTML element, and walk through how it works. This will help illustrate the use of variables, functions, and the DOM API.
JavaScript Code#
Consider the following JavaScript code:
function changeColor() {
let element = document.getElementById("example");
element.style.color = "red";
}
This script defines a function changeColor()
that changes the color of an HTML element with the id “example” to red.
Let’s break down how it works:
Function Definition: The
function
keyword is used to define a new function namedchangeColor
.Variable Declaration: Inside this function, the
let
keyword is used to declare a variable namedelement
.DOM API:
document.getElementById("example")
is a method provided by the DOM API. It finds the HTML element with the id “example” and returns it. This element is stored in theelement
variable.Changing Styles:
element.style.color = "red";
changes the color of the text inside theelement
to red. Thestyle
property is used to manipulate the CSS styles of an HTML element.
Including JavaScript in HTML#
Now, let’s see how to include this JavaScript code in an HTML file using the <script>
tag. Consider the following HTML:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<p id="example">Hello, world!</p>
<button onclick="changeColor()">Change color</button>
<script>
function changeColor() {
let element = document.getElementById("example");
element.style.color = "red";
}
</script>
</body>
</html>
In this HTML file, we have a paragraph with id “example” and a button. When the button is clicked, it calls the changeColor()
function, changing the color of the paragraph to red.
The JavaScript code is included in the HTML file using the <script>
tag. This tag is placed at the end of the <body>
section to ensure that it’s loaded after all the HTML elements have been loaded, preventing potential issues with trying to access elements that have not yet been loaded.
Remember, JavaScript code can be included in HTML files in two ways:
Inline Script: As shown in the example above, JavaScript code can be placed directly within
<script>
tags in an HTML file.External Script: Alternatively, JavaScript code can be placed in a separate
.js
file, and this file can be linked to the HTML file using thesrc
attribute of the<script>
tag.
This simple example should give you a basic understanding of how JavaScript interacts with HTML using the DOM, and how JavaScript can be included in an HTML file. We will explore more complex interactions and concepts in the coming sections.
JavaScript Basics Tutorial#
In this tutorial, we’ll learn some basic JavaScript concepts by building a simple web page with interactive features. By the end, we’ll have a page that changes an image and displays a personalized greeting upon user interaction. Make sure you have a basic understanding of HTML and CSS, and a text editor (like Notepad or Sublime Text) and a modern web browser (like Chrome or Firefox) for writing and testing your code.
Setting Up the HTML#
First, let’s set up a basic HTML structure:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Basics</title>
</head>
<body>
<h1>Welcome!</h1>
<img src="images/pic1.jpg" alt="Picture 1">
<button>Change User</button>
<script src="main.js"></script>
</body>
</html>
Save this file as index.html
. The src
attribute of the img
tag should point to an image you want to use for this exercise. Similarly, replace "images/pic1.jpg"
with the path to your second image.
Adding an Image Changer#
Next, we’re going to make the image change to another one when clicked on. We’ll achieve this by modifying the src
attribute of the img
element using JavaScript.
Create a new file, main.js
, and add the following code:
const myImage = document.querySelector('img');
myImage.onclick = function() {
const mySrc = myImage.getAttribute('src');
if(mySrc === 'images/pic1.jpg') {
myImage.setAttribute('src', 'images/pic2.jpg');
} else {
myImage.setAttribute('src', 'images/pic1.jpg');
}
};
This code first selects the img
element. Then, we define a function that will be executed when the image is clicked. This function checks the current src
of the image. If it’s the first image, it changes it to the second one. If it’s the second image, it changes it back to the first one.
Adding a Personalized Welcome Message#
We will now add a feature to display a personalized welcome message. The name for the welcome message will be saved in the browser so that even if the user leaves and comes back, the personalized welcome message will still be displayed.
Add the following code to your main.js
file:
let myButton = document.querySelector('button');
let myHeading = document.querySelector('h1');
function setUserName() {
let myName = prompt('Please enter your name.');
if(!myName || myName === null) {
setUserName();
} else {
localStorage.setItem('name', myName);
myHeading.textContent = 'Welcome, ' + myName;
}
}
if(!localStorage.getItem('name')) {
setUserName();
} else {
let storedName = localStorage.getItem('name');
myHeading.textContent = 'Welcome, ' + storedName;
}
myButton.onclick = function() {
setUserName();
};
In this code, we are first selecting the button
and h1
elements. Then, we define a function setUserName
that asks the user for their name with a popup prompt. If the user provides a name, it’s stored in the browser and used to set the text of the heading. If the user doesn’t provide a name, setUserName
calls itself again.
We then check if a name is already stored in the browser. If not, we call setUserName
to get and store a name. If a name is already stored, we use that name to set the text of the heading.
Finally, we set up an onclick
event handler on the button to allow the user to set a new name.
Conclusion#
If you followed all the steps correctly, your web page should now show a personalized welcome message and change the image when it is clicked.