Skip to main content

Lab 4: Client Side Javascript

Overview

In this lab, we will learn how to use Javascript to add interactions to a website.

To receive credit for this lab, you MUST show your work to the TA during the lab, and push it to the github before the deadline. Please note that submissions will be due right before your respective lab sessions in the following week. For Example, If your lab is on this Friday 10 AM, the submission deadline will be next Friday 10 AM. There is a "NO LATE SUBMISSIONS" policy for labs.

Learning Objectives

LO1. Understand the concept of Client side scripting using Javascript
L02. Organize Project Directory and Resources in JS project
L03. Debug JavaScript in the Browser
L04. Put together few features using JavaScript, HTML, and CSS(Bootstrap)

Part A

Pre-Lab Quiz

Complete the Pre-Lab quiz on Canvas before your section's lab time.

Part B

Clone your GitHub repository

info
You need to accept the invite to the GitHub classroom assignment to get a repository.

Github Classroom Assignment
For the next two steps, make sure to edit the name of the repository after the copying the command into your terminal.
git clone git@github.com:CU-CSCI3308-Spring2025/lab-4-client-side-scripting-<YOUR_USER_NAME>.git

Navigate to the repository on your system.

cd lab-4-client-side-scripting-<YOUR_USER_NAME>

Directory Structure and Website Overview

The website directory structure contains the HTML, CSS and javascript files for this lab.

├─Calendar/
│ ├─index.html
│ └─resources/
│ ├─js/
│ ├─ script.js
│ ├─css/
│ ├─ style.css
├─Demo/
│ ├─test.html
| ├─test.js

Debugging Javascript in the browser

Before we start the lab, let's do an activity on Debugging code in the browser.

A. Using console.log()

Step 1. In your repository, you will find a folder called test. Within that folder you will find a test.html, that you will open on your browser by double-clicking on the file.

Step 2. Now, follow the gif as shown below to access the Developer Pane in a Google Chrom browser. Developer panes are available in other browsers as well. You may need to enable the option to access Developer Tools.

Step 3. Click on the button on the HTML page. It will cause a prompt to appear. Enter your name and click "OK". You will see your name show up in the "Console" tab of the Developer pane.

Step 4. Go ahead and open the test.js file and add another console.log() statement and test it out in the browser.

You can view the output from console.log(), in the developer pane. You can also view any errors, that your program may be throwing, in this tab. Please read the errors attentively. The file and line number at which the error is occuring shows up on the right hand side of that row.

tip

It is okay to look up the errors online to fine an way to resolve them.

Watch this video to see how you can debug using the developer tools in your browser:

debugging in javascript

What are we creating today?

In this week's lab we'll build a calendar that allows the addition (and modification) of events.

Create and Initialize required files

IMPORTANT

Starting here we'll be creating and editing files within the Calendar folder of the repository.

A. Javascript - script.js

To ensure appropriate responses to user events, we will write javascript code. For reusability and maintainability purposes, it would be ideal to house all the javascript code in an external javascript file, in this case, script.js.

In your repository, you should find script.js file under resources/js.

B. CSS - style.css

In resources/css you will find a style.css file that has custom style rules for some of the HTML elements for the Calendar. You may edit this as needed to enhance the calendar website.

C. HTML - index.html

You should find index.html, with the starter code for the website, in the root of the Calendar folder. All the UI elements to be displayed will be included in this file. Before we start editing the file to add more functionality, let's link all the resources that we'll need for this webpage to function as needed.

Include project resources in your index.html -

  1. You will notice that the Bootstrap library and the style.css file have already been included in the head of the index.html.

  2. Now, let's include the javascript file we created for this project. We will be adding this file in the <body> of the HTML file at the very end.

danger

Please make sure to use Relative paths

<!-- Replace file.js with the appropriate path to script.js. Please use relative paths -->
<script src="file.js"></script>

Implement Features

Citing GenAI usage

Please remember to add all the prompts used with a Gen AI tool to complete any portion of the lab to a text file called genAI_usage.txt. You will be submitting this with the rest of the files for this lab.

Failure to cite the usage of Gen AI will result in a 0 for the lab.

Preview the provided code

Open the index.html file in a browser of your choice. It should look like the image below.

provided

Currently the Create Event button will not be functional since we haven't added any function to react to the button click.

Create Modal

  • A Modal component is a dialog box/popup window that appears on top of the currently displayed page.
  • We will create and use the same Modal for the purpose of Creating and Updating an event on the calendar.
  • You can refer to this resource for more information on modal.
  • In future steps, the Modal title and Modal body shown in the image below will be updated.

In this section, we will initialize the modal with primitive functionalities.

Step 1: Include the HTML for a Bootstrap Modal in index.html

USING GENAI TO GENERATE HTML for the Modal

You can use any GenAI tool to generate the HTML for the Modal. Make sure to meet the requirements as mentioned below. Also, you are required to include the prompts used as mentioned above in the writeup.

1: Include Modal starter code:

To start with, let's use this Modal

Set the id of the Modal to be event_modal

2: Form:

Now, let's modify the Modal body to include a form with the fields listed below.

<div class="modal-body"> <form> <!-- Include form fields to gather the information listed below. --> </form></div>
  • Event Name - A Textbox. Set the id property to be event_name.
  • Weekday - A Dropdown with Days of the week as options. Use <select> element. Set the id property to be event_weekday.
  • Time - A Time picker. Set the id property to be event_time and type property to be "time" as well.
  • Event Modality - Use a dropdown with two options - "In-Person" or "Remote". If “In-person” option is selected, then the "Location" and "Attendees" fields should be shown. If “Remote” option is selected, then "Remote URL" and "Attendees" fields should be shown. Set the id property to be event_modality.
  • Location - A textbox. Set the id property to be event_location.
  • Remote URL - A textbox. User will enter a Meeting URL (Zoom, MS Teams etc.). Use appropriate text to make this apparent to users. Consider using the placeholder attribute of the <input> tag. Set the id property to be event_remote_url.
  • Attendees - A textbox. User should enter the names of the attendees separated by commas. Use appropriate text to make this apparent to users. Consider using the placeholder attribute of the <input> tag. Set the id property to be event_attendees.
tip

Make sure to use appropriate bootstrap classes with the HTML elements for the style rules to take effect.

3: Validation:

For each event that is created/updated, there should certain fields, like name of the event, time of the event etc., that should be filled for the event to make practical sense. Add appropriate validations to your event modal fields. Refer to this resource to learn about the various validations that are available.

One validation that you MUST implement for this lab:

  • The value entered in "Remote URL" field is actually a URL. This can be done by specifying a regular expression for URL in the the pattern attribute of the input element. Here is an example of how to use the pattern attribute:
<input type="text" pattern="^[A-Z].+" />

4: Update Location Options based on Modality:

Next, we need to conditionally display the "Location" or "Remote URL" fields, in the modal form, based on the selected option in event modality dropdown. To do so, we need to implement a function updateLocationOptions() in script.js. For now, assuming that the implementation of updateLocationOptions() function exists in the JS file, let's call it on the onchange event in the <select> element.

<!-- "this.value" passed to updateLocationOptions() refers to the text in the "value" attributeof the option that is chosen by the user --><select class="form-control" id="event_modality" required onchange="updateLocationOptions(this.value)"> <option value="in-person" default>In Person</option> <option value="remote">Remote</option></select>
info

Javascript functions are always called on HTML elements that will trigger an event which will then lead to a response(s). In the example above, the visibility of certain form fields are determined based on the users selection of modality through the dropdown. Hence, the responding Javascript function needs to listen for changes to the value in the dropdown field of the form.

5: Submit Buttons: Add "Close" and "Create Event" buttons to the Modal. If you already have the buttons for the Modal, update them appropriately. The "Create Event" button should save the data form and the "Close" button should close the Modal. We will add an event to the Create Event button to call the saveEvent() function in the script.js file. saveEvent() is a function we will implement later in the lab.

You can copy over the below code to add a "Create Event" button.

<button class="btn btn-primary" type="button" onclick="saveEvent()">
Create Event
</button>

When creating an event, the modal should open and form fields should be empty.

New Calendar Event Form

When creating a new event, the modal should open with empty fields. You will notice that for the dropdowns, the values default to the first option in the dropdown.

create event

Step 2: Opening Modal when the Create Event button is clicked

We will add two attributes to the Create Event button to enable it to launch the Modal when clicked. You will see below that we have added the data-bs-toggle and data-bs-target attributes for this purpose. Update this in your index.html file.

<button
class="btn btn-primary mt-3"
data-bs-toggle="modal"
data-bs-target="#event_modal"
>
Create Event
</button>

Step 3: Adding functions for interactions in Javascript - script.js

ATTEMPT ON YOUR OWN

To understand how javascript interacts with HTML, you are encouraged to complete this portion on your own based on the instructions. Read the instructions and provided information carefully.

Toggling between Locations based on Modality

If the modality for an event is "in-person", then we show a location textbox, and if it's "remote", we should show a remote url textbox.

Saving Events

When the user clicks on the Save Event button on the Modal, we are calling the saveEvent() function. In your script.js file add a function as shown below:

function saveEvent() {}

This function should do the following:

  1. Read the values from the form within the modal. You can use the `document.getElementById()` function to fetch these values.
  2. Save the values in an array, called events, of JSON objects. Declare this array outside of the function.

Here is what each element of the array could look like:

const eventDetails = {
name: // name of the event from the form,
weekday: //weekday of the event from the form,
time: //time of the event from the form,
modality: //modality of the event from the form,
location: //if the modality is "In-person" then this has a value and remote_url is null,
remote_url: //if the modality is "Remote" then this has a value location is null,
attendees: //list of attendees from the form
};
  1. Check if the event details were stored correctly in the events array.

    i. Add a console.log() to print the contents of the events array.
    ii. Refresh your index.html page in your browser.
    iii. Create a new event through the modal and click on the Save Event button.
    iv. Now open the developer console and see if the events array shows details of the event as you entered them.

    Note: If any of the values show up as "undefined", you need to double check if you read the values from the form correctly.
  2. Add the event to the Calendar on the UI. We will call a function called addEventToCalendarUI() for this purpose. You need to pass the event details for the current event to this function. We will add code to this function in the next section.

  3. Reset the form within the modal. You can do this by using the reset() method of the form element. Below is an example:

//Assuming that the id of the form is "data-form"
document.getElementById('data-form').reset();

Displaying Events on the UI

  1. The saveEvent() function will call this function to help display the event's details on the calendar UI. So let's declare this function:
function addEventToCalendarUI(eventInfo) {}
  1. Before we proceed, we will create one more helper function to build the HTML for each individual event card that should be displayed on the calendar UI.

a. Let's create the createEventCard(eventDetails) function

function createEventCard(eventDetails) {}

b. Within this function, create a div element using the document.createElement() function.

let event_element = document.createElement('div');

c. We will add some bootstrap classes to this to enhance it's appearance. You are also welcome to add your custom CSS style rules instead.

event_element.classList = 'event row border rounded m-1 py-1';

d. Let's create one more div, using the document.createElement(), as shown above in b.. Call this variable info

e. Add all the event details to the innerHTML of this element. Here is an example:

info.innerHTML = 'Event Details';

You are strongly encouraged to use templated strings to simplify appending data from variables with a string. Alternately, you can use standard string concatenation.

Parsing the eventDetails JSON object - When you want to read the data within the eventDetails here is how you can do it as shown in the example below:

let name = eventDetails.name;

f. We will now append the info div to the event_element div we declared above. Since the info div should be nested within the event-element div, we will employ the `appendChild()` function.

event_element.appendChild(info);

g. Finally, we will return event_element from this function.

return event_element;
  1. Coming back to the addEventToCalendarUI() function, we will call createEventCard() function and pass to it the eventInfo received and store the returned value to a variable.
let event_card = createEventCard(eventInfo);
  1. Now, we need to add this event card to the appropriate day of the week on the Calendar. To do this, we will fetch the div element from the HTML for a given day using the document.getElementById(). Hint: you can use the weekday attribute of the event to fetch the correct div

  2. Use the appendChild() similar to how it was used in the createEventCard() function to append this event_card to the div fetched in 4.

  3. Finally, refresh the index.html in your browser. With the added event(s) it should look something like the image below.

calendar

info

If you refresh your browser window as you are testing these functions, the newly created calendar events(if any) will disappear, from the UI and the JS array because these changes to the HTML DOM are in-memory, which is cleared when you reload a page.

Part C

Add Colors to your event cards based on the category of events

1. Add a category field to the modal form

You need to add an additional field to the modal form called "Category". You can pick any list of categories like, academic, work etc. Your form would now look as follows:

category

2. Change the background colors of the event cards based on the category

When you save the event, based on the category of the event, you should update the background color of the event. The final view of the calendar after these changes would look similar to what you see below. You have the creative freedom to choose any colors for the different categories.

eventcolored

Extra credit

Update Events

Add update event functionality such that:

  • When you click on an event, it opens the modal with the values for the form fields pre-filled from the event that was clicked on.
  • You are able to update all/any of the fields
  • When you click on the Save Event button, the event card on the calendar reflects the updated values.

Submission Guidelines

Upload all files

Please remember to upload the genAI_usage.txt file in the submission folder as well.

Commit and upload your changes

1. Make sure you copy your files for submission into your local git directory for this lab, within a "submission" folder that you need to create.
2. Run the following commands at the root of your local git directory, i.e., outside of the "submission" folder.

git add .
git commit -m "add submission"
git push
3. Submit a link to the GitHub repository on Canvas.

Once you have run the commands given above, please navigate to your GitHub remote repository (on the browser) and check if all the files have been updated/uploaded. Once that is done, please submit a link to your repository on Canvas.

You will be graded on the files that were present before the deadline. If the files are missing/not updated by the deadline, you could receive a grade as low as 0. This will not be replaced as any new pushes to the repository after the deadline will be considered as a late submission and we do not accept late submissions. Please do not submit a regrade request for this.

Regrade Requests

Please use this link to raise a regrade request if you think you didn't receive a correct grade.

Rubric

CriteriaDescriptionPoints
Part A - Lab QuizComplete Lab Quiz on Canvas20
Project Setup & File OrganizationCorrectly includes script.js in index.html using a relative path2
Modal Implementation- Adds Bootstrap modal in index.html with id="event_modal"
- Includes all required form fields (Event Name, Weekday, Time, Modality, etc.)
- Implements appropriate Bootstrap styling for modal elements
- Ensures modal opens and closes when clicking on the create event button
10
Form Validation- Implements required validation for empty fields (Event Name, Time, etc.)
- Validates Remote URL using the correct regex pattern in pattern attribute
2
Event Creation & Data Handling- Implements saveEvent() function to capture form data and store it in an array of JSON objects
- Properly structures event objects in the events array with all required properties
- Resets form fields using the reset() method after saving an event
15
Displaying Events on Calendar UIImplements createEventCard() function to generate an event card dynamically
- Correctly appends event cards to the corresponding weekday column in the calendar UI
- Applies Bootstrap styling for event cards
12
Modality-based Field Display LogicImplements updateLocationOptions() to toggle between "Location" and "Remote URL" fields
- Ensures dropdown selection dynamically updates visible fields without page refresh
5
Event Categorization & Color CodingAdds a "Category" field to the modal form with at least three distinct categories
- Changes event card background colors based on selected category
10
Citation of Gen AI UsageAll prompts used with a Gen AI tool have been clearly listed in the genAI_usage.txt file3
Extra Credit - Update Events FunctionalityClicking on an event opens the modal pre-filled with its details
- Allows modifications and updates the event on the calendar UI upon saving changes
- Ensures updated events persist correctly and retain modifications after modal interaction
15
In-class check-inYou showed your work to the course staff.20
Total Score100 + 15(EC)

Please refer to the lab readme or individual sections for information on file names.