{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Javascript\n", "[Required Video: CS50W - Lecture 5 - Javascript](https://www.youtube.com/watch?v=x5trGVMKTdY) Watch this before you do the reading. \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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.\n", "\n", "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.\n", "\n", "## What is JavaScript?\n", "\n", "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).\n", "\n", "## What Can JavaScript Do?\n", "\n", "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:\n", "\n", "- **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.\n", "- **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.\n", "- **User Interaction**: JavaScript can react to user actions like clicks, mouse movements, and key presses, and execute code in response.\n", "- **Animation**: JavaScript can control multimedia, create images, and even animate them.\n", "\n", "## How Does JavaScript Fit into Web Development?\n", "\n", "JavaScript is an essential part of any web application. Here's how it fits into the bigger picture:\n", "\n", "- **HTML** is used to structure the content of the web page, creating a skeleton of sorts.\n", "- **CSS** is then used to format this structured content, adding colors, positioning elements, setting fonts, and more.\n", "- **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.\n", "\n", "## Capabilities of JavaScript\n", "\n", "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:\n", "\n", "## Changing HTML Content\n", "\n", "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.\n", "\n", "Here's a simple example. Suppose you have a paragraph element in your HTML:\n", "\n", "```html\n", "

Hello, world!

\n", "```\n", "\n", "You can use JavaScript to change the content of this paragraph:\n", "\n", "```javascript\n", "document.getElementById(\"example\").innerHTML = \"Hello, JavaScript!\";\n", "```\n", "\n", "After running this JavaScript code, your HTML paragraph will now read \"Hello, JavaScript!\".\n", "\n", "## Modifying CSS Styles\n", "\n", "JavaScript can also manipulate the styles of an HTML document. This allows you to change the look and feel of your website dynamically. \n", "\n", "Consider an HTML element with the id \"example\":\n", "\n", "```html\n", "

Hello, world!

\n", "```\n", "\n", "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:\n", "\n", "```javascript\n", "let element = document.getElementById(\"example\");\n", "element.style.color = \"white\";\n", "element.style.backgroundColor = \"black\";\n", "```\n", "\n", "After running this JavaScript code, your HTML paragraph will now have white text on a black background.\n", "\n", "## Reacting to User Events\n", "\n", "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.\n", "\n", "For example, you can use JavaScript to define a function that will be executed when a button is clicked:\n", "\n", "```html\n", "\n", "```\n", "\n", "```javascript\n", "document.getElementById(\"myButton\").onclick = function() { \n", " alert(\"Button clicked!\"); \n", "};\n", "```\n", "\n", "In this example, when the user clicks the button, an alert box will pop up with the message \"Button clicked!\".\n", "\n", "\n", "## DOM\n", "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!\n", "\n", "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.\n", "\n", "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.\n", "\n", "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.\n", "\n", "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.\n", "\n", "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!\n", "\n", "## Diving into JavaScript Syntax\n", "\n", "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:\n", "\n", "```javascript\n", "let greeting = \"Hello, World!\";\n", "```\n", "\n", "In this example, we've declared a variable named `greeting` and assigned it the string value \"Hello, World!\".\n", "\n", "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:\n", "\n", "```javascript\n", "let greeting = \"Hello,\";\n", "let name = \" World!\";\n", "let fullGreeting = greeting + name; // \"Hello, World!\"\n", "```\n", "\n", "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:\n", "\n", "```javascript\n", "let number = 10;\n", "if (number > 5) {\n", " console.log(\"The number is greater than 5.\");\n", "}\n", "```\n", "\n", "And here's an example of a `for` loop, which prints the numbers 1 through 5 to the console:\n", "\n", "```javascript\n", "for (let i = 1; i <= 5; i++) {\n", " console.log(i);\n", "}\n", "```\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "## Working with the DOM\n", "\n", "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.\n", "\n", "Here's an example of how to select an element by its ID and change its text content:\n", "\n", "```javascript\n", "document.getElementById(\"myElement\").textContent = \"New text!\";\n", "```\n", "\n", "And here's how you can change the style of an element:\n", "\n", "```javascript\n", "document.getElementById(\"myElement\").style.color = \"red\";\n", "```\n", "\n", "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:\n", "\n", "```javascript\n", "let newParagraph = document.createElement(\"p\");\n", "newParagraph.textContent = \"This is a new paragraph.\";\n", "document.body.appendChild(newParagraph);\n", "```\n", "\n", "## Listening for Events\n", "\n", "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:\n", "\n", "```javascript\n", "let button = document.getElementById(\"myButton\");\n", "button.addEventListener(\"click\", function() {\n", " alert(\"Button clicked!\");\n", "});\n", "```\n", "\n", "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.\n", "\n", "## Ensuring DOM Readiness: The DOMContentLoaded Event\n", "\n", "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 `` 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.\n", "\n", "Consider the following example:\n", "\n", "```javascript\n", "function handleClick(event) {\n", " // handles a click event\n", "};\n", "const elem = document.querySelector(\"#myelement\");\n", "elem.addEventListener('click', handleClick);\n", "```\n", "\n", "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`.\n", "\n", "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.\n", "\n", "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:\n", "\n", "```javascript\n", "// A function for attaching events to DOM elements\n", "function setupEvents() {\n", " const elem = document.querySelector(\"#myelement\");\n", " elem.addEventListener('click', handleClick);\n", "};\n", "\n", "// Attach our setup function to DOMContentLoaded\n", "document.addEventListener('DOMContentLoaded', setupEvents);\n", "```\n", "\n", "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.\n", "\n", "\n", "## A Simple JavaScript Example\n", "\n", "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.\n", "\n", "### JavaScript Code\n", "\n", "Consider the following JavaScript code:\n", "\n", "```javascript\n", "function changeColor() {\n", " let element = document.getElementById(\"example\");\n", " element.style.color = \"red\";\n", "}\n", "```\n", "\n", "This script defines a function `changeColor()` that changes the color of an HTML element with the id \"example\" to red.\n", "\n", "Let's break down how it works:\n", "\n", "1. **Function Definition**: The `function` keyword is used to define a new function named `changeColor`.\n", "\n", "2. **Variable Declaration**: Inside this function, the `let` keyword is used to declare a variable named `element`.\n", "\n", "3. **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 the `element` variable.\n", "\n", "4. **Changing Styles**: `element.style.color = \"red\";` changes the color of the text inside the `element` to red. The `style` property is used to manipulate the CSS styles of an HTML element.\n", "\n", "## Including JavaScript in HTML\n", "\n", "Now, let's see how to include this JavaScript code in an HTML file using the `\n", "\n", "\n", "\n", "```\n", "\n", "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.\n", "\n", "The JavaScript code is included in the HTML file using the `\n", "\n", "\n", "```\n", "\n", "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.\n", "\n", "### Adding an Image Changer\n", "\n", "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.\n", "\n", "Create a new file, `main.js`, and add the following code:\n", "\n", "```javascript\n", "const myImage = document.querySelector('img');\n", "\n", "myImage.onclick = function() {\n", " const mySrc = myImage.getAttribute('src');\n", " if(mySrc === 'images/pic1.jpg') {\n", " myImage.setAttribute('src', 'images/pic2.jpg');\n", " } else {\n", " myImage.setAttribute('src', 'images/pic1.jpg');\n", " }\n", "};\n", "```\n", "\n", "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.\n", "\n", "### Adding a Personalized Welcome Message\n", "\n", "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.\n", "\n", "Add the following code to your `main.js` file:\n", "\n", "```javascript\n", "let myButton = document.querySelector('button');\n", "let myHeading = document.querySelector('h1');\n", "\n", "function setUserName() {\n", " let myName = prompt('Please enter your name.');\n", " if(!myName || myName === null) {\n", " setUserName();\n", " } else {\n", " localStorage.setItem('name', myName);\n", " myHeading.textContent = 'Welcome, ' + myName;\n", " }\n", "}\n", "\n", "if(!localStorage.getItem('name')) {\n", " setUserName();\n", "} else {\n", " let storedName = localStorage.getItem('name');\n", " myHeading.textContent = 'Welcome, ' + storedName;\n", "}\n", "\n", "myButton.onclick = function() {\n", " setUserName();\n", "};\n", "```\n", "\n", "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.\n", "\n", "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.\n", "\n", "Finally, we set up an `onclick` event handler on the button to allow the user to set a new name.\n", "\n", "### Conclusion\n", "\n", "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.\n", "\n", "## Further Reading\n", "* [Mozilla: What is Javascript?](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript)\n", "* [Mozilla Javascript Basics](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercises\n", "\n", "### A. Javascript Exercises\n", "1. **[Complete all tutorials](https://www.w3schools.com/js/js_intro.asp)**\n", "2. **[Complete the examples](https://www.w3schools.com/js/js_examples.asp)**\n", "3. **[Complete the quiz](https://www.w3schools.com/js/js_quiz.asp)**" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.3" } }, "nbformat": 4, "nbformat_minor": 1 }