FDT FE-103 (Java Script) Sprint Summary

Modified on Fri, 24 May at 6:02 PM


Usage Directions:


This is FE-103 Sprint Sprint. Revising the entire content is estimated to require one hour of effort, assuming you have prior exposure to the same tech stack. We recommend approaching this task in parts for a more effective revision process.


All the best!




TABLE OF CONTENTS



Topic 1: Browser Events


Browser Events


  • What is it?

Browser events are actions or occurrences that happen within a web browser, such as a user clicking a button, scrolling a page, or submitting a form. In JavaScript, you can listen for these events and write code to respond to them.

  • Where is it used?

Browser events are used in web development to make web pages interactive and responsive. 

  • How is it used?

    • Event Listener Registration: Use the addEventListener() method to register an event listener on a specific HTML element or the global window object. This tells the browser to listen for a specific event on that element.

    • Event Type and Callback: Specify the type of event you want to listen for (e.g., "click", "scroll", "submit") and provide a callback function that will be executed when the event occurs.

    • Event Handling: Inside the callback function, write the code that should run when the event is triggered. This can include modifying the DOM, updating data, making API requests, or performing any desired action.

Example code snippet:

const button = document.getElementById("myButton");

function handleClick(event) {
  console.log("Button clicked!");
  // Additional code to handle the click event
}

button.addEventListener("click", handleClick);


  • Takeaways / Best practices:

    • Browser events allow JavaScript code to respond to user interactions and other occurrences within the web browser.

    • Use addEventListener() to register event listeners and specify the event type and the callback function that will be executed when the event occurs.

DOMContentLoaded Event


What it is:

The DOMContentLoaded event is triggered when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

Where it is used:


It is used in JavaScript to ensure that code is executed only after the document has been fully loaded and the DOM (Document Object Model) is ready for manipulation.

How it is used:


1. Add an event listener to the document object for the DOMContentLoaded event.
2. Inside the event listener function, write code that manipulates or interacts with the DOM elements.

Code snippet:

document.addEventListener('DOMContentLoaded', function() {
  // Code to be executed when the DOM is ready
  var element = document.getElementById('myElement');
  element.innerHTML = 'DOM is ready!';
});


Takeaways / Best practices:
- Use the DOMContentLoaded event to make sure your JavaScript code is executed at the right time, after the document has been fully loaded.
- Placing JavaScript code just before the closing </body> tag can also ensure that the DOM is ready, but using the DOMContentLoaded event is preferred as it allows code to be placed anywhere.
- Avoid using inline JavaScript code in HTML files, and instead use external JavaScript files which are included in the head or just before the closing </body> tag for better organization and maintainability.

Event Object


What it is:

Event Object is a built-in object in JavaScript that represents an event happening in the browser, such as the user clicking a button or the page finishing loading.

Where it is used:


- Event Object is used in event handling functions to access information about the event that occurred.
- It is commonly used in event listeners or callback functions to perform specific actions based on user interactions or browser events.


How it is used:
- The Event Object provides various properties and methods to interact with the event, such as event type, target element, and event coordinates.

Code snippet example:


// Creating an event listener for a button click
const button = document.querySelector('button');

function handleClick(event) {
  console.log(event.type); // "click"
  console.log(event.target); // target element that was clicked
}

button.addEventListener('click', handleClick);


Takeaways / Best practices:
- The Event Object is automatically passed as an argument to event handling functions.
- Utilize the properties and methods of the Event Object to access and manipulate event-related information.
- Use the `event.preventDefault()` method to prevent the default behavior of certain events, such as submitting a form or following a link.
- Be aware of the event bubbling and capturing phases to handle events correctly on nested elements.


Topic 2: Event Bubbling


Event Bubbling


What it is:

Event bubbling is a mechanism in JavaScript where an event triggered on a nested element will propagate up through its parent elements until it reaches the root of the document.

Where it is used:
Event bubbling is used in event handling to make it easier to handle multiple elements with similar behaviors or to attach event handlers to dynamically created elements.

How it is used:
To use event bubbling in JavaScript:

1. Attach an event listener to a parent element that you want to handle events for.
2. When an event is triggered on a nested/child element, the event will propagate up through its parent elements.
3. Handle the event on the parent element by checking the event target or using event delegation.

Example:

HTML:

<div id="parent">
  <div id="child">
    <button id="inner-button">Click me!</button>
  </div>
</div>

const parent = document.getElementById("parent");

parent.addEventListener("click", function(event) {
  // Check if the event target was the inner button
  if (event.target.id === "inner-button") {
    console.log("Button clicked!");
  }
});


In this example, when the button with the id "inner-button" is clicked, the event will bubble up through the parent elements until it reaches the "parent" element. The event listener attached to the "parent" element will then handle the event and log a message.

Takeaways / Best Practices:
- Event bubbling allows for more efficient event handling by reducing the number of event listeners needed.
- Use event delegation by attaching event listeners to parent elements, especially when dealing with dynamically created elements.
- Be cautious when using event.stopPropagation() to stop event propagation, as it can interfere with other event handlers.


Topic 3: HTML Forms


HTML Forms


  • What it is:

HTML Forms are used to collect user input and send it to a web server for processing. They are commonly used in websites for activities like user registration, login, surveys, etc.

  • Where it is used:

HTML Forms can be used in combination with JavaScript to enhance their functionality and perform various actions based on user input.

  • How it is used:

    • Create an HTML form using the <form> tag and add various input elements like text fields, checkboxes, radio buttons, dropdowns, etc., using appropriate tags.

    • Use the <input> tag with the "type" attribute set to "submit" to add a submit button which will trigger form submission.

    • Optionally, use the <button> tag with a click event listener in JavaScript to perform custom actions instead of form submission when the button is clicked.

    • Attach an event listener to the form's submit event in JavaScript using the addEventListener method to execute a function when the form is submitted.

    • Inside the event listener function, prevent the default form submission behavior using the preventDefault method to handle form submission manually and perform validations or other operations.

    • Access the form elements and their values using the DOM (Document Object Model) methods like getElementByIdgetElementsByNamequerySelector, etc.

    • Process the form data as required, such as sending it to a server using AJAX or performing client-side operations like data manipulation or validation.

    • Optionally, display success messages or error messages based on the form processing results.

Example code snippet:

<form id="myForm">
  <input type="text" name="name" placeholder="Name">
  <input type="email" name="email" placeholder="Email">
  <input type="submit" value="Submit">
</form>

<script>
  const form = document.getElementById('myForm');
  form.addEventListener('submit', function(event) {
    event.preventDefault(); // Prevents default form submission behavior

    // Access form values
    const name = form.elements['name'].value;
    const email = form.elements['email'].value;

    // Perform form data processing
    if (name && email) {
      // Send form data to server or perform other actions
      console.log(`Form submitted: Name - ${name}, Email - ${email}`);
      form.reset(); // Optionally reset form after submission
    } else {
      // Show error message for missing values
      console.log('Please fill in all fields.');
    }
  });
</script>



Best practices:

  • Always validate user input on both the client-side and server-side to ensure data integrity and security.

  • Use appropriate form input types and attributes for better user experience and accessibility.

  • Provide clear instructions, error messages, and validation feedback to users.

  • Apply consistent styling and design to enhance visual appeal and usability.

  • Consider using libraries or frameworks like jQuery or React to simplify form handling and validation.


Topic 4: Local Storage, Session Storage and Cookies


Local storage, session storage, and cookies are all client-side storage options available in web browsers, each serving different purposes and having different characteristics. Here's a concise summary of each, including their usage and limitations:


Local Storage

Local storage is a method for storing data locally within the user's browser that persists even after the browser window is closed. Data stored in local storage is not sent automatically to the server with every request, making it a secure place for storing non-sensitive, non-temporary user data.


- Capacity: Typically up to 5MB.

- Accessibility: Data can be accessed from any window or tab in the same origin.

- Lifespan: Data persists until explicitly deleted via scripts or cleared by the user.

- Usage Example:

 

localStorage.setItem('username', 'JohnDoe');
console.log(localStorage.getItem('username'));  // Output: JohnDoe
localStorage.removeItem('username');



Session Storage

Session storage is similar to local storage but has a shorter lifespan. Its data is cleared when the page session ends—that is, when the tab or window is closed. It's useful for storing data that should not persist beyond the current browsing session.


- Capacity: Up to 5MB.

- Accessibility: Data is only available within the same tab or window.

- Lifespan: Data is cleared when the tab or window is closed.

- Usage Example:

 

sessionStorage.setItem('sessionKey', '00123');
console.log(sessionStorage.getItem('sessionKey'));  // Output: 00123
sessionStorage.removeItem('sessionKey');

  


Cookies

Cookies are data stored in small text files on the user’s device and are sent back to the server with every HTTP request. Cookies are primarily used for managing user sessions, tracking user behavior, and storing user preferences.


- Capacity: Limited to about 4KB.

- Accessibility: Sent with every HTTP request to the domains they belong to, which can affect performance if overused.

- Lifespan: Can be set to expire (delete) on a specific date or after a specific length of time. Can also be created as session cookies which expire when the browser is closed.

- Usage Example:

 

document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
console.log(document.cookie);  // Output: username=JaneDoe

  


Summary

- Local Storage: Good for storing large amounts of data that persists beyond the session across multiple windows or tabs from the same origin.

- Session Storage: Ideal for storing data that should not be preserved once the session ends, available only within the window or tab where it was stored.

- Cookies: Best for sending data back to the server and managing user sessions, but limited in size and can impact performance if not used judiciously.


These storage methods play a vital role in enhancing user experience by efficiently managing data directly on the client's browser.


Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article