Lab 4: Client Side Javascript
Overview
In this lab, we will learn how to work with javascript to add functionality to an HTML page. You will create a web page and add functionality to it using JavaScript.
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 Static Typing and Dynamic TypingL02. 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
1. Static Typing vs. Dynamic Typing
Please make sure you have understood this topic before you proceed.
A. Static Typing
So far, you have worked with C++ to build codebases. So we will use that as the language for explanations below.
Variables
You must have noticed that when you create variables, you always specify a datatype to indicate the nature of the data that will be stored in that variable and also to let the system know at compile time as to how much memory to allocate for that variable. This is what we call Static Typing. Languages like C, C++, Java, C# are examples of statically typed languages.
For eg:
int a = 0; // at compile time, we know that 'a' is an integer variable
Functions
Given that every piece of data that we pass around in the program have types associated with them, if we were to pass arguments to a function or return a value from a function we would need to declare them in the function signature. For eg:
//Let's say we want a function that returns the sum of 2 numbers
// We have to specify the return type of the function to match the value we are returning.
// We also need to mention the types of the arguments we are accepting in this function.
int sum(int a, int b){
return a+b;
}
B. Dynamic Typing
Here we will use Javascript for examples.
Variables
Javascript is a classic example of a dynamically typed language. In JS, you will notice that we do not have definitive types. Instead we have a generic idea of declaring a variable using keywords like var
, let
, const
. The type of the variable is determined at run time based on the value assigned to it. This is referred to an inferred type of the variable. Let's look at an example:
var a; //Currently this is just a variable that has no type associated with it.
a = 5; //In this step, since 5 is an integer, a's inferred type will now be int.
In the newer standard of JS, ES6, let
and const
were introduced as the standards to overcome drawbacks associated with var
. For more information read this article
Since types are determined at run time and variables can assume different types in the lifecycle of the program, these languages are called Dynamically Typed languages. Languages like Python, Perl, PHP etc. are also examples of Dynamically Typed Languages.
The other thing to note is that such languages are not compiled but interpreted and do not generate any build artifacts like object files or executables.
Functions
Because variables in JS can assume the type of the data it stores, we do not need to specify any types in function declarations - not for return types or for the function parameters. Similar to variables, we just use the keyword function
to indicate that we are defining a function.
For eg:
//Let's write a function to return the sum of 2 numbers
function sum(a, b) {
return a + b;
}
Clone your GitHub repository
Github Classroom Assignment
- Using an SSH key
- Using a Personal Access Token (PAT)
git clone git@github.com:CU-CSCI3308-Fall2024/lab-4-javascript-<YOUR_USER_NAME>.git
git clone https://github.com/CU-CSCI3308-Fall2024/lab-4-javascript-<YOUR_USER_NAME>.git
Navigate to the repository on your system.
cd lab-4-javascript-<YOUR_USER_NAME>
2. 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
3. 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.
It is okay to look up the errors online to fine an way to resolve them.
B. (recommended). Using the debugger in the browser
Watch this video to see how you can debug using the developer tools in your browser:
4. What are we creating today?
In this week's lab we'll build a calendar that allows the addition and modification of events. The objectives are to:
- learn the basics of Javascript,
- it's ability to modify the HTML DOM, update the elements and their properties in a webpage, and
- learn to use of the event-driven programming paradigm of Javascript.
5. Create and Initialize required files
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
. The starter code provided in the file lists all the functions you are required to implement for this lab. Please do not delete any of them.
B. CSS - Create style.css
Create a style.css
file in your directory at the location shown in the directory structure. Include the following CSS in your style.css
file for styling. You may include more style rules as needed.
You can refer to lab 3 to revise how to link CSS files to HTML.
body {
height: 100%;
background-color: #f2f2f2;
}
.event:hover {
cursor: pointer;
}
.hidden {
visibility: hidden;
height: 0;
}
#calendar {
height: 100vh;
}
C. HTML - index.html
You should find index.html
with the standard HTML outline in the root of the Calendar
folder. All the UI elements to be displayed will be included in this file. Before we start creating the elements, let's link all the resources that we'll need for this webpage to function as needed.
<!DOCTYPE html><html> <head> <title>Calendar</title> <!-- TO DO: include all external resources - Bootstrap libraries, index.js and style.css --> </head> <body> <!-- Calendar elements --> </body></html>
- Include Bootstrap in your index.html - For ease of development and better presentation, we will make use of the Bootstrap library. Copy over the below resource links into the
<head>
after line 5 of theindex.html
file.
<!-- Bootstrap CSS library --><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"/>
<!-- Bootstrap JS library --><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<!-- Bootstrap icons library --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css"/>
Include project resources in your index.html - Now, let's include the resource files we created for this project. These resources should be linked in the
<head>
of theindex.html
file after the bootstrap resources.dangerPlease make sure to use Relative paths
i. Javascript:
<!-- Replace file.js with the appropriate path to script.js. Please use relative paths -->
<script src="file.js"></script>ii. CSS:
<!-- Replace file.css with the appropriate path to style.css. Please use relative paths -->
<link rel="stylesheet" href="file.css" />
6. Implement Features
To complete this lab successfully, please make sure to read the comments in the code snippets given! Install this TODO Highlight extension within VSCode to enable highlights on all the TODOs in the comments. This should help you locate and complete tasks more easily.
1. Initialize Calendar
A. UI - index.html
Let's implement the HTML to create the calendar.
Step 1: Include an onload
event in the <body>
element to execute initializeCalendar()
function when the web page has completed loading.
<!-- Replace myFunction() with initializeCalendar() -->
<body onload="myFunction()"></body>
Step 2: Create a <div>
element with class="container"
within the <body>
element. This div will serve as the parent element for the calendar.
- You can refer to this resource to choose a suitable container for your calendar.
<div class="container">
<!-- You may choose another container class of your liking -->
<!-- All elements of the webpage will be added within this div -->
</div>
Step 3: Inside the above <div>
, create another <div>
element with id="calendar"
. This will house the calendar that will be created in a Javascript function in the next part.
<div id="calendar" class="row"></div>
B. Javascript - script.js
As learnt in class, Javascript can be used to create and modify HMTL elements. To do so, we will write javascript code to initialize the UI elements for the calendar, including creating the days of the week and adding the events for the relevant days.
Learn before you proceed!
Here are some useful resources you should read through before proceeding to the next step:
1. Document.createElement() - Helps you create new HTML elements in Javascript
var newDiv = document.createElement('div'); // To create a `div` element
var newPara = document.createElement('p'); // To create a `p` element
2. Element.append() - Helps you add content to an HTML element. It can be string objects or HTML elements. Does not return any values.
var newDiv = document.createElement('div');
var newAnchor = document.createElement('a');
newDiv.append(newAnchor);
3. Node.appendChild() - Helps you add, strictly, HTML elements to another HTML element. It returns a reference to the HTML element that was appended and can be stored in a variable for future use in the program.
const paragraph = document.createElement("p");
document.body.appendChild(paragraph);
Now let's use this knowledge to start building the contents of the page.initializeCalendar()
is the method that will help you build the interface for the Calendar. We will be implementing helper functions along the way. Make sure to read the instructions and follow them carefully.
Step 1: First, copy over the content of initializeCalendar()
function, from the code block below, and fill out the calendarElement
variable by reading the TODO in line 7.
/* The function initializeCalendar() initializes the Calendar for your events and it gets called `onload` of your page.We will complete the TODOs to render the Calendar in the next few steps. */// You will be implementing this function in section 2: Create Modalfunction initializeCalendar() { // Step 1: Initialize the modal (No changes required here). initializeEventModal(); // @TODO: Step 2: Select the calendar div element by its id. Replace '...' with the correct code to get the div. // Hint: Use either `document.getElementById('id')` or `document.querySelector('#id')` to find the element. const calendarElement = ... // Step 3: Loop through each day in the CALENDAR_DAYS array(No changes required here). // This array contains the days of the week (e.g., 'Monday', 'Tuesday', etc.). CALENDAR_DAYS.forEach(day => { // @TODO: Step 4: Uncomment the following line and complete the function call createBootstrapCard(day) function // var card = // @TODO: Step 5: Filling below lines and add the created card to the calendar element using appendChild(). // // @TODO: Step 6: Uncomment the below line and call createTitle(day) function. // var title = // @TODO: Step 7: Filling below lines and add title to the card. Use appendChild() // // @TODO: Step 8: Uncomment the below line and call createEventIcon(card) function. // var icon = // @TODO: Step 9: Filling below lines and add icon to the title. Use appendChild() // // @TODO: Step 10: Uncomment the below line and and call createEventDiv() function. // var eventsDiv = // @TODO: Step 11: Filling below lines and add eventsDiv to the card. Use appendChild() // // @TODO: Step 12: Filling below lines and do a console.log(card) to verify the output on your console. // }); // @TODO: Step 13: Uncomment this after you implement the updateDOM() function // updateDOM()}// end of initializeCalendar()
Step 2: Implement the createBootstrapCard(day) function which creates a card for all days in the week.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function and fill out the card
variable by reading the TODO in line 2.
function createBootstrapCard(day) { // @TODO: Use `document.createElement()` function to create a `div` var card = // Let's add some bootstrap classes to the div to upgrade its appearance // This is the equivalent of <div class="col-sm m-1 bg-white rounded px-1 px-md-2"> in HTML (card.className = 'col-sm m-1 bg-white rounded px-1 px-md-2'); // This the equivalent of <div id="monday"> in HTML card.id = day.toLowerCase(); return card;}
Now, inside the initializeCalendar()
function, finish the TODOs from line numbers 10 - 12.
Output: After this step, open index.html
in your browser and the webpage should look similar to this:
Step 3: Implement the createTitle(day) function which creates weekday as the title.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function and fill out the title
variable by reading the TODO in line 3.
function createTitle(day) { // Create weekday as the title. // @TODO: Use `document.createElement()` function to create a `div` for title const title = ... title.className = 'h6 text-center position-relative py-2'; title.innerHTML = day; return title;}
Now, inside the initializeCalendar()
function, finish the TODOs from line numbers 13 - 15.
Output: After this step, when you refresh the webpage the output should look similar to this:
Step 4: Implement the createEventIcon(card) function which adds a button for adding an event.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function and fill out the icon
variable by reading the TODO in line 2.
function createEventIcon(card) { // @TODO: Use `document.createElement()` function to add an icon button to the card. Use `i` to create an icon. const icon = ... icon.className = 'bi bi-calendar-plus btn position-absolute translate-middle start-100 rounded p-0 btn-link'; // adding an event listener to the click event of the icon to open the modal // the below line of code would be the equivalent of: // <i onclick="openEventModal({day: 'monday'})"> in HTML. icon.setAttribute('onclick', `openEventModal({day: "${card.id}"})`); return icon;}
Now, inside the initializeCalendar()
function, finish the TODOs from line numbers 16 - 18.
Output: After this step, when you refresh the webpage the output should look similar to this:
Step 5: Implement the createEventDiv() function which will create the container div
that will be populated with events.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function and fill out the eventsDiv
variable by reading the TODO in line 2.
function createEventDiv() { // @TODO: Use `document.createElement()` function to add a `div` to the weekday card, which will be populated with events later. const eventsDiv = // We are adding a class for this container to able to call it when we're populating the days // with the events eventsDiv.classList.add('event-container'); return eventsDiv;}
Now, inside the initializeCalendar()
function, finish the TODOs from line numbers 19 - 22.
Output: Here is how your calendar will look like (with debugger opened) with the weekday divs added.
Do inspect
and click on the console
tab to see the logs.
2. 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.
A. Javascript - script.js
Step 1: Implement the initializeEventModal() function which will refer to the modal that is created in index.html
with id = event-modal
.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function and fill out the EVENT_MODAL
variable by reading the TODO in line 2.
function initializeEventModal() { // @TODO: Create a modal using JS. The id will be `event-modal`: // Reference: https://getbootstrap.com/docs/5.3/components/modal/#via-javascript EVENT_MODAL =}
Step 2: Copy the content for openEventModal() which will open the event modal when you click on the Calendar icon. We will be adding more code to this function later.
function openEventModal({id, day}) {
EVENT_MODAL.show();
}
Now, go ahead and click the +
icon on the Calendar to check if you are able to see an empty modal as shown in the below image.
Example Modal:
B. UI - index.html
1: Include Modal starter code:
To start with, let's use this 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 beevent_name
. - Weekday - A Dropdown with Days of the week as options. Use
<select>
element. Set theid
property to beevent_weekday
. - Time - A Time picker. Set the
id
property to beevent_time
andtype
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 beevent_modality
. - Location - A textbox. Set the
id
property to beevent_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 theid
property to beevent_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 theid
property to beevent_attendees
.
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 theinput
element. Here is an example of how to use thepattern
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>
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 submit the form and the "Close" button should close the Modal.
You can copy over the below code to add a "Create Event" button.
<button id="submit_button" class="btn btn-primary" type="submit">
Create Event
</button>
Make sure to add these buttons inside the <form>
element, else they will not function as expected.
- We are specifying the id for the "Create Event" button since its text will be updated to "Update Event" by a function in
script.js
depending on the action to be performed.
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.
Update/View Existing Calendar Event Form
On clicking an existing event in the calendar, the modal should open and the form fields should be populated with the details of that event. A sample view of “Update Event”, after implementing the javascript functionality, modal is shown below -
C. Updating location options via Javascript - script.js
Now we come back to javascript to implement updateLocationOptions() function, from 6.2.B.4. If the modality is "in-person", then we show a location textbox, and if it's "remote", we should show a remote url textbox.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function and fill out the location
and remoteUrl
variables by reading the TODO in line 2.
After that, implement the TODO from line 7 to display and hide the necessary fields based on user selection.
function updateLocationOptions(modality_value) { // @TODO: get the "Location" and "Remote URL" HTML elements from the modal. // Use document.querySelector() or document.getElementById(). const location = //get the "Location" field const remoteUrl = // get the "Remote URL" field // @TODO: Depending on the "value" change the visibility style of these fields on the modal. // Use conditional statements. if (modality_value == "in-person") { }}
3. Update DOM
Now, we need to display the events created, on the Calendar in the UI. Similar to how we completed the initializeCalendar(), let's complete the helper functions createEventElement(id), createTitleForEvent(event) first, and call them inside the updateDOM() function defined below.
You may see the usage of template strings in some parts of the code. You may refer to this resource to learn more.
A. Javascript - script.js
Step 1: Implement the createEventElement() function to create an event for the calendar.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function and fill out the eventElement
variable by reading the TODO in line 2.
After that, replace the property of eventElement
in line 8 based on the instructions on lines 6-7.
function createEventElement(id) { // @TODO: create a new div element. Use document.createElement(). var eventElement = ... // Adding classes to the <div> element. eventElement.classList = "event row border rounded m-1 py-1"; // @TODO: Set the id attribute of the eventElement to be the same as the input id. // Replace <> with the correct HTML attribute eventElement.<> = `event-${id}`; return eventElement;}
Step 2: Implement the createTitleForEvent() function which creates a title for the event.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function.
function createTitleForEvent(event) { var title = document.createElement('div'); title.classList.add('col', 'event-title'); title.innerHTML = event.name; return title;}
Step 3: Now before getting into the implementation of updateDOM() function, let's first understand how we will fill our calendar with sample events.
If you look at the begining of script.js, you will find the CALENDAR_EVENTS
array with 1 sample event.
Please do not add this code snippet for CALENDAR_EVENTS as it is already present at the top of the script.js file. This is only for reference.
To simulate existing events on the calendar,
- this array of events will be used to initialize the calendar when it is first loaded.
- Add one more event to this array.
- Each event must have
name
,day
,time
,modality
,location
,url
,attendees
. - Give each field a suitable value (similar to what would be expected from the user for that field).
- We will be using JSON representation to store this data as can be seen below. What is json?
Let's work on the updateDOM()
function.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function. Please follow the TO DO instructions in the comments and complete the code.
function updateDOM() { const events = CALENDAR_EVENTS; events.forEach((event, id) => { // First, let's try to update the event if it already exists. // @TODO: Use the `id` parameter to fetch the object if it already exists. // Replace <> with the appropriate variable name // In templated strings, you can include variables as ${var_name}. // For eg: let name = 'John'; // let msg = `Welcome ${name}`; let eventElement = document.querySelector(`#event-<>`); // if event is undefined, i.e. it doesn't exist in the CALENDAR_EVENTS array, make a new one. if (eventElement === null) { eventElement = createEventElement(id); const title = createTitleForEvent(event); // @TODO: Append the title to the event element. Use .append() or .appendChild() } else { // @TODO: Remove the old element while updating the event. // Use .remove() with the eventElement to remove the eventElement. } // Add the event name const title = eventElement.querySelector('div.event-title'); title.innerHTML = event.name; // Add a tooltip with more information on hover // @TODO: you will add code here when you are working on for Part C. // @TODO: On clicking the event div, it should open the modal with the fields pre-populated. // Replace "<>" with the triggering action. eventElement.setAttribute('<>', `openEventModal({id: ${id}})`); // Add the event div to the parent document .querySelector(`#${event.day} .event-container`) .appendChild(eventElement); }); //updateTooltips(); // Declare the function in the script.js. You will define this function in Part B.}
Now, call this updateDOM() function inside the initializeCalendar()
function - Uncomment line number 37 in the initializeCalendar()
function.
Output: Now, you should be able to see the events as well on the calendar as seen in the below screenshot.
4. Open and Update Event
For now we can only see the events that are listed inside the CALENDAR_EVENTS array. We will proceed to add the functionalities to create, open and update the events on the Calendar by just clicking on the event.
A. Javascript - script.js
Step 1: Let's create and add an event to the calendar.
This function will be called on clicking the +
icon on a given week day on the Calendar. You can go back and take a look at the initializeCalendar()
function to see that we have attached the openEventModal()
function to the click
event of the +
icon.
We'll make use of innerHTML to read or write the contents of an HTML element. You can see in the example below how to use innerHTML
to add content to the <p>
element.
const para = document.createElement('p');
para.innerHTML = 'This is some sample text';
Initially, our openEventModal({ id, day })
function only opened the Modal when the +
icon on the Calendar was clicked. We will be replacing it with the below code to create an event or update an event if it already exists.
Complete the TODOs as mentioned in the comments.
function openEventModal({ id, day }) { // Since we will be reusing the same modal for both creating and updating events, // we're creating variables to reference the title of the modal and the submit button // in javascript so we can update the text suitably const submit_button = document.querySelector("#submit_button"); const modal_title = document.querySelector(".modal-title"); // Check if the event exists in the CALENDAR_EVENTS by using `id` // Note that on the first try, when you attempt to access an event that does not exist // an event will be added to the list. This is expected. let event = CALENDAR_EVENTS[id]; // If event is undefined, i.e it does not exist in the CALENDAR_EVENTS, then we create a new event. // Else, we load the current event into the modal. if (!event) { event = { name: "", day: day, time: "", modality: "", location: "", url: "", attendees: "", }; // @TODO: Update the innerHTML for modalTitle and submitButton // Replace <> with the correct attribute modal_title.<> = "Create Event"; submit_button.<> = "Create Event"; // Allocate a new event id. Note that nothing is inserted into the CALENDAR_EVENTS yet. // @TODO: Set the id to be the length of the CALENDAR_EVENTS because we are adding a new element } else { // We will default to "Update Event" as the text for the title and the submit button modal_title.innerHTML = "Update Event"; submit_button.innerHTML = "Update Event"; } // Once the event is fetched/created, populate the modal. // Use document.querySelector('<>').value to get the form elements. Replace <> // Hint: If it is a new event, the fields in the modal will be empty. document.querySelector("#event_name").value = event.name; // @TODO: Update remaining form fields of the modal with suitable values from the event. // Location options depend on the event modality // @TODO: pass event.modality as an argument to the updateLocationOptions() function. Replace <> with event.modality. updateLocationOptions(<>); // Set the "action" event for the form to call the updateEventFromModal // when the form is submitted by clicking on the "Creat/Update Event" button const form = document.querySelector("#event-modal form"); form.setAttribute("action", `javascript:updateEventFromModal(${id})`); EVENT_MODAL.show();}
Step 2: Implement updateEventFromModal().
Now that we added or updated events in the previous step, let's make sure the CALENDAR_EVENTS array is also up to date with this information. The updateEventFromModal()
function will be called when you click on the "Create/Update Event" submit button on the modal.
In the HTML, the "Create/Update Event" button should be within the <form>
element for this functionality to work correctly.
The function declaration is already provided in the script.js file. Copy over ONLY the contents of the function. Please follow the TO DO instructions in the comments and complete the code.
function updateEventFromModal(id) { // @TODO: Pick the modal field values using document.querySelecter(<>).value, // and assign it to each field in CALENDAR_EVENTS. CALENDAR_EVENTS[id] = { name: document.querySelector('#event_name').value, }; // Update the dom to display the newly created event and hide the event modal updateDOM(); EVENT_MODAL.hide();}
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
1. Display tooltip for an event
- Create and display a popup tooltip when we hover over an event.
- This function will be called from
updateDOM()
. Refer to the comments on how to do so.
Helpful resources: Bootstrap Tooltip - Please go through the example, shown there, in detail.
function updateTooltips() {
// @TODO: Display tooltip with the Name, Time and Location of the event.
// The formatting of the contents of the tooltip is up to your discretion.
}
Submission Guidelines
Commit and upload your changes
Make sure you have all the files added in the directory structure specified. Run the following commands inside your root git directory (in your lab5-javascript-<username> directory).
git add .
git commit -m "Added all js, html, css and data files for calendar"
git push
Once you have run the commands given above, please navigate to your GitHub remote repository (on the browser) and check if the changes have been reflected.
You will be graded on the files that were present before the deadline. If the files are missing/not updated, 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.
Regrade Requests
Please use this link to raise a regrade request if you think you didn't receive a correct grade. If you received a lower than expected grade because of missing/not updated files, please do not submit a regrade request as they will not be considered for reevaluation.
Rubric
Criteria | Description | Points |
---|---|---|
Part A - Lab Quiz | Complete Lab Quiz on Canvas | 20 |
Part B - Create & Link Files | Create the files in the directory structure and link the appropriate resources to the index.html | 5 |
Part B - Initialize Calendar | Add functionality to initialize the calendar | 10 |
Part B - Create Modal | Initialize the modal with primitive functionalities | 10 |
Part B - Implement updateDOM() | Add functionality to display the events created on the Calendar in the UI. | 10 |
Part B - Open and Update Event | Add the functionalities to create, open and update the events on the Calendar. | 15 |
Part C - Add tooltips | Appropriate tooltips are displayed when the mouse is hovered over the event | 10 |
In-class check-in | You showed your work to the TA. | 20 |
Total Score | 100 |
Please refer to the lab readme or individual sections for information on file names.