Free Full Course Learn JavaScript DOM Coding Projects Interactive and Dynamic Web Pages Bonus 100+ Page Ebook FREE

Learn JavaScript DOM Coding Projects Interactive and Dynamic Web Pages

First 25 Students Get it FREE https://skl.sh/3h7H68r

Modern coding exercises to develop your JavaScript coding skills from the most commonly asked for questions about JavaScript

Explore the JavaScript DOM how to 

  • Email AutoResponder
  • DOM Element Maker
  • Functions Arrow Plus
  • AJAX fetch JSON data
  • Collision Detection
  • Dynamic Page Elements
  • Events interactive Elements
  • Animation Element Moving

Following coding exercises are designed to help develop your JavaScript skills on applying JavaScript to create interactive and dynamic content on web pages.
Web page dynamic welcome messageThe web page exercise is a simple example of how you can get input from a user, and then apply that input value within JavaScript to create a dynamic web response.  Input field provides a way for the user to interact with the web page.  To get the input value, select the page element, then from within that element property values there is a property name value which is holding the input field value.  Return the value in a variable then use that value within a string response which then gets output into the web page as a customized message to the web user.Function Expression vs Declaration vs Arrow One of the most asked questions is about functions, and which ones to use.  There are different ways to create function and this exercise is designed to highlight how to use them.  Along with the arrow format for functions and use of the “this” keyword to reference the current object within the function scope.  Create 3-page counters using different functions, expression, declaration, and arrow format.  Counters will all work independently as the value of the total is contained within the instance of the function object using this.Dynamic JavaScript DOM page counters Element Objects examplesDynamically create page buttons that can be used to count totals separately.  Create a button to output all the result totals.  Only using JavaScript NO HTML elements.   Store values of the page elements, get the values from the page elements and output the results to the web page.DOM create Page elements adding styleCreate interactive elements that can store the current color value input an array, for later use.  Also creates buttons to update the body background color to the value of the button text.  Color style and events with Dynamic Elements DOM.When multiple elements need to be created, best practice is to create a function to handle the element creation, this will avoid repetition of code. This exercise will demonstrate how to create elements, how to store values into element objects, how to update style properties of elements, and how to remove elements from the page.   Storing the values of the elements and retrieving value of elements and using those element values as new page elements are created.  Use of appendChild() vs append() allows the code to return the element that was appended to the parent.   This saves a line of code where the return of the function can be combined with adding the element that was just created into the page.Dynamic JavaScript Slider from JSON data Dynamic Carousel Slider from JSON data Sliders are a commonly used component within web pages.  They provide a way to display content and create interaction for the user.  When the web page user is engaged in the page element, they are more likely to read and remember the content being presented.  Sliders, slideshow, Carousel are various ways this component is referred to on the web.  The functionality of the component allows for cycling through elements, which can be images text or others.  The carousel or slider is a slideshow for cycling through a series of content that the user can control.  They can move through the content with the previous or next item buttons. The content that gets displayed in the carousel, is not contained in the JavaScript file.  This example will help demonstrate how to separate data, which then can be updated without having to update the code.  The code and logic within the code should work independently of the data.  Change the JSON file data and should change the output in the HTML web page without breaking the JavaScript code.  AJAX JSON data with fetch using promisesExercise to demonstrate using, AJAX in JavaScript with the Fetch method and how to get multiple JSON data files content with the PromiseAll Method connecting to multiple URLs within one block of code.  Exercise lesson to practice making fetch requests, using async and await with fetch and how you can connect to multiple endpoints using promiseAll and return the results as one object value.  This example will use three separate JSON files, all with the same data structure, which will make it possible to combine the data into one object once all the responses complete separately.  PromiseAll provides a way to use promises and join the results as one chaining them together.  Fetch can be used to connect to external files, like JSON and return the results of those data files into JavaScript code.  The data needs time to load, that is why promises are used to handle the data once it’s ready and returned from the endpoint.   Using async and await in the function can set up the promise to wait until a response is returned.  Fetch can do the same with the chaining of then promises to handle the data once its arrived.  You can also use promiseAll if there are multiple files that need to load data into one object.  Once all the data is ready then the file contents can be used in the code and output on the page.  JavaScript DOM element Collision detectionThe overlap of elements is what can be referred to as collision detection.  This is a standard part of most games, when moving page elements to be able to detect the position and calculate if they are overlapping.This exercise is designed to test and learn more about how to check for overlap of elements that move on the page.  It will demonstrate how to set up movement of page elements, and output the values needed to calculate the collision between two-page elements.  Moving elements on the page can be done by tracking the key presses from the user.  Creating an object that will store the keydown and keyup boolean values of specific keys, can then be used within the animation frame to move the elements depending on the boolean values within the key object.  If the key is pressed down the object will have a true value, which can then be used to determine which keys are being pressed down and apply the movement accordingly. Page Element Collision detection part 2The overlap of elements is what can be referred to as collision detection.  This is a standard part of most games, when moving page elements to be able to detect the position and calculate if they are overlapping.  This exercise will also demonstrate how to simplify the collision detection using getBoundingClientRect() method to get the element boundaries and dimensions within the checking function.  Using getBoundingClientRect() method can eliminate the need to track element positions in an object and return back the needed X, Y, height, width values when needed.  Using the same overlap formula as before and placing the returned object values of the element provides a quick checking function that can be used for collision detection on any element.  Within the function arguments it only requires the elements objects which can also be selected or used from preselect element variables.   This exercise is designed to test and learn more about how to check for overlap of elements that move on the page.  It will demonstrate how to set up movement of page elements, and output the values needed to calculate the collision between two-page elements.DOM Element Catcher Game Set UpObjective of the game is to click the elements, as they drop, try to land them on the moving platform to score. First lesson is to set up the basic game board and simple interaction with elements and movement. This exercise will demonstrate how to create elements, how to move elements by updating style values, and how to create interactive elements that respond to a user’s interaction.   Use the requestAnimationFrame() method to create smooth movement between elements on the page.Element Movement and Collision DetectionExplore how to apply game logic and create animation within the game.  Moving the elements on the page once the user clicks them.  This is the action that the game is waiting for from the user, and it initiates the sequence of the game.  The use of JavaScript Math random method allows for the creation of more engaging content.  Random positions create non repetitive game interactions that make the game more engaging.  Automatic movement of the paddle will create the challenge in the game play, as the play must now be able to anticipate the position and plan for an intersection of the two elements.  This is the challenge of the game that the player accomplishing.  For gameplay to be effective the interactions must be possible but not always certain.Adding collision detection between the two elements will allow the code to create the necessary logic to check for a successful outcome from the user action.DOM element catching Game Final CodeCreate and update the code with game logic, the allows a player to get information and have information on what is expected.  There should also be a way to end the game and provide the player a way to restart and play again.Best way to achieve smooth game play is to play through the game and apply any changes that help smooth the player experience.  Test and debug any issues that might occur.Once the game is playable and the game catching.How to Create a Web Form that can send emails using your Gmail accountExercise : Create an HTML form with fields for the data that you want to send. Setup the JavaScript to validate the form input values, and create an object of data to send to the Apps Script endpoint. HTML Send Email via Apps Script How to send an email from a HTML form, using Google Apps Script and JavaScript. Front-end code to send emails from html forms. Exercise : Create an HTML form with fields for the data that you want to send. Setup the JavaScript to validate the form input values, and create an object of data to send to the Apps Script endpoint. Send POST request to Google Apps Script In this lesson the application will be updated to make a fetch request using the POST method to the Google Apps Script endpoint, and insert the form field data into a spreadsheet. Exercise : Update the fetch method to POST, include the form field data as an object in the POST request body contents. Create the Google Apps Script endpoint using a webapp to receive the GET and POST request data from the AJAX request from JavaScript. Send Email when the form is submitted Send an email to your email address with the form content when the web form is submitted. Send a response confirmation email to the user’s email address from the submitted form content. Exercise : Update the Google Apps Script to send emails to the user’s email address in response to the web form submission, send a second email to your email when the form data is submitted with the form field information.

Select from the interactive projects from the lessons of the course.

Create a web interaction, get the users info from an input field and then update the page content with the users name creating a custom welcome message for the user.

Share your projects to the class, projects can be shared using the source code, screenshots, live web URLs and repos at Github.

  • Web page dynamic welcome message
  • Function Expression vs Function Declaration This Counter
  • Dynamic JavaScript DOM page counters Element Objects examples
  • DOM create Page elements adding style
  • Slider from Dynamic Elements using JSON data
  • AJAX JavaScript Fetch with PromiseAll Method for multiple URLs
  • JavaScript DOM element Collision detection
  • Collision detection Checker of DOM page elements Part 2
  • Element Catcher Game Part 1 set up
  • Element Catcher Part 2 movement and collision detection
  • Element Catcher Part 3 Final Game
  • HTML Send Email via Apps Script
  • Send POST request to Google Apps Script
  • Send Email when the form is submitted

Create a page welcome message :

  1. Get the user name in the input field
  2. When the button is pressed add an event that get the user name and creates a welcome message on the page
  3. Add a check to ensure the length of the input is larger than 3 characters long

Page counters with functions :

  1. Select all the page buttons
  2. Create a function expression that will increment the counter on button press
  3. Create a function expression with the arrow format that will track and increment the count on the page
  4. Create a function declaration that will track and increment the count on the page.

Dynamic Page counters with JavaScript :

  1. Create a global object to set the number of buttons to be created
  2. Create a main page element that will contain all the new elements
  3. Create a function to create page elements, adding the element type to a parent object.  Include a parameter in the function for the inner content of the element.
  4. Loop through and create all the buttons, set a default total of 0 for each one.  On click create a function that will update and output the current value of this element total.  You can add styling to the buttons
  5. Add a class of “btn” to each new button so that they can be distinguished from the main total tally button.   Create a button that will output all the current button total results.
  6. When the tally button is clicked create a function that will select all the elements with a class of “btn” and loop through them.
  7. For each element with the class of “btn” create a new list item element, output that into an unordered list on the main page.  The list item contents should show the element total and the element textContent.  You can also select the style to match the button style property values.

Page elements Events and Style Exercise :

  1. Using JavaScript, create two buttons on the page.
  2. Add a click event to the first button, that when pressed should list out all the stored color values from the holding array.  When pressed create page elements that have the color value from the holding array, and are clickable elements.  Once clicked the element should be removed from the page.
  3. The second button should store the color value from the input field into a holding array.
  4. The second button should also create a page element button, that has the text content of the input field color value.
  5. On change of the input value update the background color to match the input field value.

JSON slides navigate slides with JavaScript Exercise :

  1. Select the main slider element as a variable named slider in JavaScript.
  2. Create a function that gets invoked once the DOM content loads. Give the function a name of adder()
  3. Within adder() create the slides, using the data from the JSON file apply the text title, html content, and styling to the slide elements.  Add them to the page.
  4. If it’s the first item in the data then add the class of active to the first one only
  5. Add an event listener to the buttons, when clicked check if it contains the next class, create a function named mover() to handle the result
  6. Get the current element with the active class.  Using traversing, get the next sibling to the current element, if no next element exists then select the first child of the parent slider element.
  7. Get the previous element, if it’s null then select the last child of the parent slider.
  8. Remove the active class for the current element, add the active class to the new element either previous or next.

AJAX request example code exercise :

  1. Create 3 page buttons to make requests.  Set up an element on the page to show the output of the results.
  2. Using the first button on click, connect to a json file and return the contents back using fetch.   Output the results of the file onto the web page.
  3. The second button uses async on the main request function, and await to move to the next function once the request completes.  Output the results of the file data into the web page.
  4. Create an array of the paths to several JSON files, with the same object structure in each file.  
  5. Once the third button is pressed, use Promise.all to make fetch requests to each JSON file.  Nest the map function within the Promise.all request, so that the code can iterate through each JSON file.  Once all the requests are completed then output the content into the web page from the JSON files.

Set up movement of page elements and track the position exercise :

  1. Create a function that allows for the creation of page elements as we can then dynamically add elements to the page as needed.  Give the function a name of adder() to get the parent element that the new element will be appended to.  Create the element using the string value of the element tag.  Add the inner HTML content for the element and also add a class using the string value.
  2. Create 4 page elements, 2 boxes that will be moved, and 2 areas to output the box coordinates and dimensions.
  3. Create a global game object that can track the animation frame, contains the x,y (horizontal,vertical) position of each box, and that contains the h,w (height and width) of each box.  These values then can be used to update the position.
  4. Set up an object named keyz to track which keyboard keys will be used for element movement.  Add 8 key code names as property names and set the values to false.  This will be updated once the key is pressed.
  5. Add event listeners on the document that listen for keydown and keyup events.  If the keys from the keyz object pressed match the object property name, set the value to true on press down and false on up.   This can now be used for the element movement.
  6. Create and Launch the mover() function which will handle page element movement on key presses.
  7. Within the mover() function add conditions to check which keys are true, update the game object x,y for each box accordingly.  Also apply a condition to check to ensure that before the movement is allowed that the element is within the boundaries of the main container object element.
  8. Update the style values of properties left and top for each box with the new game x,y values for each.
  9. Output the x,y,h,w of each element to the page as they move; these values should change with the new x,y coordinates of the element.  These will be used to calculate the collision of the elements.

Moving exercise to check for element overlap:

  1. create move output areas to show the current stats of the element and the collision values.  Update the style of the element if an overlap occurs.
  2. Create a new element in the center to use within the collision check function.
  3. Create a new function that requires two parameters, one for each element to check.  Get the boundaries of the element.
  4. Create a function col() which can check the boundaries and return a boolean value if the two elements are overlapping.  Use this formula to check for overlap of the elements between the various boxes on the screen.
  5. Update element styling and output info styling depending on the result of the collision detection.

Create basic interactive elements that move exercise:

  1. Create a function that can set up new page elements.  Using parameters of the parent element the new element should be added too.  The element tag type string name.  The inner html content of the element and a class that gets added to the new elements that are created.
  2. Add an event listener that waits for the DOMContentLoaded to invoke an init function that creates the game board content.
  3. Add click events to the new elements
  4. Create random background colors for the new element boxes that are created.  Math.random().toString(16).slice(2,8)
  5. When the element box is clicked add the active class to the element.
  6. Create a new function that will handle the animation of elements. This function should be invoked once the start game is pressed, and within itself run the requestAnimationFrame() to the function.
  7. Within the mover() function get all the active elements, get the offset top value of the element, and increment it by the game speed value.  Apply the new top style position value to the element to make it move.
  8. Add a condition to stop the element from moving by removing the active class from the element once it reaches the bottom of the game container.

Update the game object and detect collision of page elements exercise:

  1. Create a paddle element that can move from side to side.
  2. Add values in the game object, to be able to stop the game play, and keep track of a score.  Create different speeds for the paddle and the falling box elements.  Track the main page width so that elements can be randomly placed within the game screen width.
  3. Randomly set the x axis values for the box elements so they are spread out randomly across the top of the screen.
  4. Once the paddle goes off the container then set it to move the opposite direction.
  5. Add the paddle movement within the animation frame.  
  6. Within the animation frame check the position of the active elements, checking for both x and y axis overlaps of corners of the elements.
  7. If the position of the box plus its height is greater than the paddle y position, and the box y position is less than the paddle plus its height then there is an overlap on the y axis.
  8. If there is overlap of the values of the 2 objects, and box x position is less than paddle x plus the width, and also the box plus its width is greater than the paddle x position then there is a hit on the x axis. 
  9. If a hit occurs then remove the element.
  10. If the element ends up having a y position off screen, then reset the random x position and update the y to the top of the screen again.  
  11. The gameplay will continue removing only the elements that hit the paddle and resetting the misses back to the top.
  12. Add tracking of the hits and misses, add the element x,y and the paddle x,y to the message area for debugging if needed.
  13. Make adjustments to the position of the page elements to enhance the game screen area.

Game play debugging and final adjustment exercise

  1. Play through the game to ensure the proper messaging for the player
  2. Add an end game for the game over once all the elements have been landed on the paddle.
  3. Provide a way for the player to restart the game, reset the scoring and all the game play to start again.
  4. Change the elements to have their own drop speeds, apply various updates to make the game more challenging.

Exercise : Create an HTML form with fields for the data that you want to send.  Setup the JavaScript to validate the form input values, and create an object of data to send to the Apps Script endpoint.

  1. Add HTML input fields for the user to be able to enter information.  Apply CSS styling as needed to style your form fields
  2. Using JavaScript select the input fields as JavaScript variables
  3. Create an event that invokes a function named submitter() when the form submit button is clicked
  4. Using e.preventDefault(); to prevent the default action of the form submission to prepare for AJAX.
  5. Add conditions on the input field values, set up a variable to add content to if errors are caught.
  6. If errors are caught in the conditions, output them in a new element that gets created with JavaScript.  
  7. Set a timeout to remove the error element and reset the input field border colors back to default.
  8. Create an object the contains all the form input data with property names that match the data.

Exercise : Update the fetch method to POST, include the form field data as an object in the POST request body contents.  Create the Google Apps Script endpoint using a webapp to receive the GET and POST request data from the AJAX request from JavaScript.   

Create a web app with Google Apps Script GET method.  

  1. create a new project 
  2. Using the method doGet(e) create a new function that will return the e parameters from the URL request object.  
  3. Create and return the e parameters as a string value.  return ContentService.createTextOutput(JSON.stringify(e))
  4. Set the MimeType to JSON setMimeType(ContentService.MimeType.JSON)
  5. Deploy a new webapp set the configuration to execute as your account, and who has access to Anyone
  6. Copy the web app URL to the JavaScript application as the GET fetch endpoint url.
  7. Try sending the fetch request to the Google Apps Script web app and check the response data in the console.

Exercise : Update the Google Apps Script to send emails to the user’s email address in response to the web form submission, send a second email to your email when the form data is submitted with the form field information.

Create a test function to send emails using data from an object

  1. Create a function named sendMyEmail that will handle the sending of the emails using an object as the source for the data.
  2. Create a function to validate an email address before trying to send an email to that user.  This should be included to avoid errors in the Google Apps Script which would result in a CORS issue on the web form.
  3. Create a testing function with simulated object data that would be coming from the form.  Include the rowval that is set from the sheet row that was inserted.
  4. Using the MailApp service, use the sendEmail method to send an email, with an object of parameters for the method.   Set the to, subject and htmlBody to the desired values for the email.  You should use the form data structure for the object, to simulate the form submission.
  5. Check if the email is valid that the user provided, if it is then using the sendMail send a custom response to the user.
  6. Using the test data ensures that you are able to send the email, and accept permissions for the app to use the mailApp service.  This is required otherwise the app will not be able to send emails.
  7. Move the sendEmail function to the doPost() method, using the real submitted data. 
  8. Deploy the webapp for the endpoint, if you create a new webapp then ensure you copy the new URL to the web application.

You should be able to send emails to the user, to yourself and also the data should still be added into the spreadsheet whenever the form is submitted.

Leave a Comment