Isha Ponugoti
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # CS2 Lab 4 2023, JavaScript 🎰 [<<< Back to main site](https://cs.brown.edu/courses/csci0020/) <img src="https://hackmd.io/_uploads/H1NagEAT3.png" width=200> > **Due Date: 11/2/2023** > **Need help?** Remember to check out Edstem and our Website for TA help assistance. :::warning **Important Note:** This lab has a longer background and introduction information. We recommend that you read through everything and refer back to it as you complete the tasks. ::: ## Introduction Recall from the previous two labs that HTML defines the structure of the webpage, while CSS defines the style and appearance of the webpage. In this lab, we will be working with JavaScript (JS). JavaScript defines the behavior of the webpage and allows your webpage to change and interact with users, adding a level of sophistication to what you have been working on previously. ## Lab Goals ♣ - Understand the syntax of JavaScript (JS) as well as functions, variables, and callbacks - Understand what the Document Object Model (DOM) is and how JavaScript interacts with it - Learn simple JavaScript events: `onclick`, `onmouseover`, `onmouseout` ## Getting Started ♠️ You will be writing your JavaScript files in your VSCode, like you've done with your HTML and CSS files. Once you have finished writing your JS files, you will open the template HTML file in a web browser, which will take care of interpreting what you have written and turn it into an interactive web page. **This is a harder lab compared to previous labs (based on student feedback) because it is the first time we introduce concepts like variables, conditionals, and programming logic, so start early!** However, understanding JavaScript and specifically functions and variables will help immensely with Python and future programming. ## Learning Javascript ♦ Just like learning any language, it's always best to start with syntax. Here we will briefly talk about how to write a JavaScript program. Below will show you how to declare variables, do arithmetic, and write functions. Some important things to note beforehand: - All lines (with the exception of those that end with curly braces) end with semicolons - Be sure to read the documentation and use the links mentioned ### Variables Sometimes we want to store data for later use. We can do this by declaring a variable. A common way to do this is using the var keyword. For example, we could create a variable `a` with the value 5, and then easily change the value once the variable is created (for example, below we store the value 7 in the variable `a` we previously created). ```javascript= var a = 5; a = 7; ``` **Capitalization matters** in JavaScript: ```javascript= var a = 6; var A = 3; ``` In the code block above, `a` and `A` refer to different variables. ### Arithmetic JavaScript allows you to quickly perform basic arithmetic operations. Some of these operations are: - `+` → addition - `-` → subtraction - `*` → multiplication - `/` → division For example, ```javascript= var a = 7; var b = 6; console.log(a + b) ``` would print the value 13. (`console.log()` just prints out whatever is inside for us to see). **Link to resources:** https://www.w3schools.com/js/js_arithmetic.asp ### Conditionals Depending on different conditions, we might want our website to behave differently. For example, if it's nighttime we might want to shift our website to night mode. To do this, we can use a conditional if-else statement like below. The if-else statement uses a *condition*, something that’s either true or false, to determine what will happen. ```javascript= if (<condition>) { // if the condition is true do this } else { // if the condition is false do this } ``` `if (<condition>)` is true, then the portion of code between the first two curly brackets in the first section is run. `else`, the code in the second portion between the second set of curly brackets is run. The following syntax is used for comparisons that you might want to make: | JS Code | Meaning| | -------- | -------- | | `===` | equal | | `!==` | not equal | |`<=` |less than or equal| | `>=` | greater than or equal | | `<` | strictly less than | | `>` | strictly greater than | **Example 1**: ```javascript= var a = 5; var b = 7; if ( a <= b) { console.log("a is less than or equal to b"); } else { console.log("a is not less than or equal to b"); } ``` In this example, the if condition (less than or equal to) is true for the two variables *a* and *b* so the first portion of the code is run and ``"a is less than or equal to b"`` is printed to the console: **Example 2**: ```javascript= var a = 5; var b = 7; if ( a === b) { console.log("a is equal to b"); } else { console.log("a is not equal to b"); } ``` In this example, the condition would evaluate to false because a and b are not equal. Therefore only the code within the brackets for the else block will run and print ``"a is not equal to b"``. **Link to resources:** https://www.w3schools.com/js/js_if_else.asp ### Functions When we write code, there are sometimes chunks of code that we want to use multiple times in different places, but it would be a pain to copy and paste what you’ve already written EVERY time you want to re-use that chunk of code. That’s where functions come in. A **function** is a block of code that is meant to be called and executed in multiple places. **Example 1**: A function can have an input and an output. For example, we can have an add function that adds two numbers x and y, and returns their output. Consider the following code: ```javascript= function add(x,y) { return x+y; } var z = add(1,2); ``` The **function definition**, line 1, is what defines the name and parameters of the function. This function name is `add` and it needs two **parameters**, `x` and `y`. We can also think of parameters as inputs to our function (so we input `x` and `y`, and output `x+y`). The **function body**, line 2, is what the function actually does. In this case, the function calculates the sum of the given parameters (`x` and `y`) and returns it. The **function call**, line 4, is outside of the function itself, and it’s what actually tells the browser to execute the function. ==***If you don’t have a function call, your function body won’t be executed!***== In this case, we are calling the function `add`, passing in 1 as `x` and 2 as `y`. **Example 2**: A function can also take no input and return nothing: ```javascript= function hello() { console.log(“hello world”); } hello(); ``` This function takes in no arguments (still needs the parenthesis) and just prints out "hello world". It doesn’t return anything either. Again, line 4 above is the **function call**. :::warning Even if a function doesn’t have arguments, to call the function you must still add the parentheses. ::: **Link to resources:** https://www.w3schools.com/js/js_functions.asp ## Tasks ♥️ :::info **Task 0** Double click your `CS2` folder on your desktop, and create your folder for `JavaScript`. Then, create a new folder inside called `JavaScriptLab`. All your files for this JavaScript Lab should live in this folder. ::: ### Writing JavaScript For this lab, we will be using both Visual Studio Code (VSCode) and Google Chrome. To write JavaScript in the Google Chrome console: :::info **Task 1** 1. Open up a new Chrome Window. 2. Right click (two finger click on Mac) on the webpage. Click on the "Inspect" option. The right side of your screen should look like this: ![](https://hackmd.io/_uploads/By1jQD0pn.png) **Note:** After clicking inspect, the console tab should be open. If it’s not, click to open it (circled in red in the above image). ::: This console is an area where you can write code. While this lab will take you through the steps of how to code in JavaScript, a few general things to keep in mind are: - When you hit `enter`, your code will be run. If you need to write code that takes more than one line, you can press `shift+enter` to use a new line without running what you have currently written. - When you run your code by pressing `enter`, you might see another line appear that says undefined. This is not an error. It refers to the return value of what you just ran. If a function does not return anything after being called, the console prints undefined. - The console remembers what you have written. To clear the console, either: - Exit out of the tab, **OR** - Right click on the console and press “Clear Console History” (“Clear” only removes output on screen) ### Printing To print something in JavaScript, we use `console.log(`). For example, ```javascript= console.log(3); ``` would print the number 3 (as seen below). ![](https://hackmd.io/_uploads/SJ1gNw06h.png) Now it's your turn! :::info **Task 2** In the console, type: ```javascript= function hello(){ console.log("Hello World!"); } hello(); ``` This should output `Hello World!` to the console. Congratulations, you just wrote your first JavaScript program! ::: Now, let's move on to working with JavaScript within VSCode. :::info **Task 3** 1. Download the [`JS Lab Stencil HTML file`](https://drive.google.com/file/d/1MieH18fqDp6HXxiQzfr08JdTxI8fsDpO/view?usp=share_link) and put it into the `Javascript_Lab` folder you just made. 2. Open the JS Lab folder in VSCode 3. Create a new file called lab4.js in the JS Lab folder. 4. Open the "homepage.html" file in VSCode. 5. To get your JS file to work with an HTML file, you must link the files together. This is very similar to the way you link a CSS file to an HTML file. Place the following line of code before the closing body tag (`</body>`) in your homepage.html file: ```javascript! <script src="./lab4.js"></script> ``` ::: :::info **Task 4** Now it's your turn! Recalling the `add` operation from earlier, create the following functions with the appropriate names in lab4.js: - `subtract`: subtracts two numbers and returns the result - `multiply`: multiplies two numbers and returns the result - `divide`: divides two numbers and returns the result :::spoiler **Hint** Remember to use parameters in the parentheses of each function! ::: :::info **Task 5** Write a function called `rnd` that returns a random number between 0 and 255 (inclusive). - To learn how to generate a random number, check out: https://www.w3schools.com/js/js_random.asp - You’ll want to use both **`Math.random()`** and **`Math.floor()`**, and this function should look almost exactly like one of the examples above! :::spoiler **Testing your functions** If you want to test that your functions work, there are two methods to do this: 1. Try copying and pasting your code (the function definition) in the Google Chrome console, then calling each function. To call a function, make sure you pass in the appropriate arguments within parentheses (or leave parentheses empty if there are no arguments). For example, to call add above, you could write `add(2,3)` which should print out 5. 2. If you have correctly linked your JS and HTML, you can also just open your webpage in Chrome as you would normally, then open the console, and then run your functions. This way, you avoid having to copy code over, because your webpage already knows about the functions you’ve written in your javascript file. For example, if you’ve defined the rnd function in your javascript file and linked your javascript to your html, then you can open the html in chrome, click Inspect and then simply type `rnd()` in the console. When you hit enter, a random number from 0-255 should print out in the console. ::: ### The Document Object Model Now that we understand JavaScript, we can use it to change the way our website behaves. An important thing to remember from the HTML lab is the concept of nested tags. When structuring an HTML document, tags are nested within each other. This nested structure is called the document object model (DOM). The DOM is important because it gives us a way of accessing specific elements within the file. We are going to use the DOM to practice changing elements of the website. In JS, the function: :::success `document.getElementById(id)` ::: allows you to get an element with a given `id`. Once you get an element with the `id`, you are able to make changes to its properties (such as text color, background color, etc.). For example, if the first paragraph has `id="first_paragraph"` in our HTML file (recall a paragraph uses the `<p>` tag) and we want to change the color of the first paragraph text to blue, we can write in our JS file: :::success `document.getElementById("first_paragraph").style.color = "blue";` ::: Now it's your turn! :::info **Task 6** In lab4.js, write a line of code to change the **background color** of the website from blue to any other color. To do this, you should use `document.getElementById` to get the appropriate element (the body), then set the background color of that element to your new color. >You can look at homepage.html to find what element id to use and you can use this [list of object properties](https://www.w3schools.com/jsref/dom_obj_style.asp) to find what property of that element to change. :::warning **Check:** Try opening homepage.html in your Chrome browser to make sure the background color changed correctly! ::: ### Events Now that we understand how we can change elements using JS, let’s add some interaction with our site! We can add event listeners to different ids to have something happen when they are clicked (`click`), the mouse is moved (`mousemove`), the mouse is hovered (`mouseover`), etc. Here is a more comprehensive list of events. For this lab, we are going to be focusing on click events, but the general idea applies to using other events. If we want a function to occur every time an element with a given id is clicked, we can use: `document.getElementById(“<id>”).addEventListener('click', <function>);` Note that the id should again be passed in in quotes and the function should just be passed in by name. For example, we can define a function `changeBackgroundColor` that is called every time a button with `id=“button”` is clicked: ```javascript document.getElementById(“button”).addEventListener('click', changeBackgroundColor); ``` > Note we just use the NAME of the function, we don't put the `()` after it (which calls the function). This is a `reference` to a function. :::info **Task 7** Next, we are going to **add functionality to the effect button**. The effect button will toggle the visibility of the image. When you click on the effect button, the image should disappear when it is showing and reappear when it's not. Lets break it down for you: 1. In your javascript file, create a new function called `toggle`. For now, it can be empty. 2. In your javascript file, add an event handler to the effect button. Note that in the HTML, the effect button has an ID of `effect-button`. When the button is clicked, it should call the `toggle` function you just defined. 3. Give functionality to the `toggle` function. - Use a conditional to check if the image is not visible by checking if the visibility property of the image is "hidden" * `if` so, you should set the visibility property to "visible" * `else`, you should set it to "hidden" * the image you should be changing the visibility of has the id of `toggle-image` >Hint: the “if else” statement referenced in the conditionals section might be helpful here! Here’s an example of a condition that you could put inside your if statement to check if the current condition is hidden: ```javascript= if (document.getElementById("<id>").style.visibility === "hidden") { // do something } else { // do something else } ``` The triple equal sign is used for conditionals. Here you are basically asking the question: is the visibility hidden? If that question is answered “true”, then you enter the if statement. If it is false, you’ll go to the else statement. The target attribute you are trying to change within the style is called `visibility`. Note that in the if statement, we use `===` to compare, but if we were trying to set the visibility of an object to something (either "hidden" or "visible"), we would just use `=` for assignment. ::: ## Hand-In 🎲 :::success **To Hand-In Lab 4**: Come to hours and show your TA the following: 1. `Hello World!` printed in your console (Task 2) 2. The functions `subtract`, `multiply`, `divide`, and `rnd` in your `lab4.js` file (Tasks 4 & 5) 3. Your homepage with a background color other than blue (Task 6) 4. An image that disappears and reappears when you click (Task 7) Congrats! You just finished your CS2 JavaScript lab! :slot_machine: ::: <hr />

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully