Full Stack Software Engineering for Beginners

July 4th, 2023


Intermediate HTML: forms, tables, and media elements

HTML forms

HTML forms are used to collect user input and submit it to a server for processing. They allow users to enter data, make selections, and interact with a website. Forms consist of various form elements, such as text fields, checkboxes, radio buttons, dropdown lists, and buttons.

  1. Text Input: allows users to enter single-line text input
<form>
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
</form>

What does for attribute mean?

In this example, the <label> element is associated with the <input> element by using the for attribute. The value of the for attribute is set to the id of the <input> element (id="name" in this case). This association tells the browser that clicking on the label should activate or focus the corresponding input field.

When a user clicks on the "Name:" label in this example, the associated input field with id="name" will receive focus or become activated, allowing the user to interact with it easily.

Using the for attribute in <label> elements is particularly helpful for users who may have difficulty precisely clicking on small form elements. It improves accessibility by expanding the clickable area and making it easier for users to interact with form controls.

  1. Checkbox: allow users to select multiple options
<form>
  <label for="option1">
    <input type="checkbox" id="option1" name="option[]" value="Option 1"> Option 1
  </label>
  <label for="option2">
    <input type="checkbox" id="option2" name="option[]" value="Option 2"> Option 2
  </label>
</form>
  1. Radio Buttons: allow users to select a single option from a group of options
<form>
  <label for="option1">
    <input type="radio" id="option1" name="option" value="Option 1"> Option 1
  </label>
  <label for="option2">
    <input type="radio" id="option2" name="option" value="Option 2"> Option 2
  </label>
</form>
  1. Select Dropdown: provides a list of options from which users can choose a single option
<form>
  <label for="country">Country:</label>
  <select id="country" name="country">
    <option value="USA">USA</option>
    <option value="Canada">Canada</option>
    <option value="UK">UK</option>
  </select>
</form>
  1. Submit Button: triggers the form submission to the server
<form>
  <!-- form fields... -->
  <input type="submit" value="Submit">
</form>

Example HTML form code

<!DOCTYPE html>
<html>
<head>
  <title>Sample HTML Form</title>
</head>
<body>
  <h1>Sample HTML Form</h1>
  
  <form action="http://localhost:5000" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" placeholder="Enter your name"><br><br>
    
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" placeholder="Enter your email address"><br><br>
    
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" placeholder="Enter your password"><br><br>
    
    <label for="gender">Gender:</label>
    <input type="radio" id="male" name="gender" value="Male">
    <label for="male">Male</label>
    <input type="radio" id="female" name="gender" value="Female">
    <label for="female">Female</label><br><br>
    
    <label for="country">Country:</label>
    <select id="country" name="country">
      <option value="USA">USA</option>
      <option value="Canada">Canada</option>
      <option value="UK">UK</option>
    </select><br><br>
    
    <label for="interests">Interests:</label>
    <input type="checkbox" id="interest1" name="interest[]" value="Sports">
    <label for="interest1">Sports</label>
    <input type="checkbox" id="interest2" name="interest[]" value="Music">
    <label for="interest2">Music</label>
    <input type="checkbox" id="interest3" name="interest[]" value="Travel">
    <label for="interest3">Travel</label><br><br>
    
    <input type="submit" value="Submit">
  </form>
  
</body>
</html>

The action attribute specifies where to send the form-data when a form is submitted.

When the user clicks the submit button in the provided HTML code, the form is submitted. By default, when a form is submitted, the browser sends the form data to the server specified in the action attribute of the <form> tag.

Upon form submission, the browser will collect all the form field values, including the name, email, password, gender, country, and interests, and package them into an HTTP request.

HTML tables

HTML tables are used to organize and display tabular data in a structured format. Tables consist of rows (<tr>) and cells (<td>) that are organized into columns (<th> or <td> within a <tr>).

Example HTML table code

<!DOCTYPE html>
<html>
<head>
  <title>Sample HTML Table</title>
</head>
<body>
  <h1>Sample HTML Table</h1>
  <table>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
      <th>Header 3</th>
    </tr>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
    </tr>
    <tr>
      <td>Data 4</td>
      <td>Data 5</td>
      <td>Data 6</td>
    </tr>
  </table>

</body>
</html>

HTML media elements

HTML provides several media elements that allow you to embed and control different types of media content within web pages.

  1. <img>: The <img> element is used to embed images in HTML pages. It is a self-closing tag and requires the src attribute to specify the image URL.
<img src="image.jpg" alt="Image description">
  1. <audio>: The <audio> element is used to embed audio content in HTML pages. It can be used to play audio files supported by the browser. You can specify the audio source using the <source> element within the <audio> element.
<audio controls>
  <source src="audio.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
</audio>
  1. <video>: The <video> element is used to embed video content in HTML pages. It supports various video formats and provides controls for playback, volume, and fullscreen mode. Similar to the <audio> element, you can specify video sources using the <source> element within the <video> element.
<video controls>
  <source src="video.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>
  1. <iframe>: The <iframe> element is used to embed external web content or documents within an HTML page. It is commonly used to embed videos from video sharing platforms or display external web pages.
<iframe src="https://www.youtube.com/embed/VIDEO_ID"></iframe>

Example HTML media elements code

<!DOCTYPE html>
<html>
<head>
  <title>Sample HTML Media Elements</title>
</head>
<body>
  <h1>Sample HTML Media Elements</h1>
  
  <!-- Image -->
  <img src="image.jpg" alt="Image description">
  
  <!-- Audio -->
  <audio controls>
    <source src="audio.mp3" type="audio/mpeg">
    Your browser does not support the audio tag.
  </audio>
  
  <!-- Video -->
  <video controls>
    <source src="video.mp4" type="video/mp4">
    Your browser does not support the video tag.
  </video>
  
  <!-- Embedded Content -->
  <iframe src="https://www.youtube.com/embed/VIDEO_ID"></iframe>
  
</body>
</html>

CSS layout techniques: positioning, floats, and flexbox

CSS positioning

CSS positioning is a technique used to control the position and layout of elements on a web page. There are several positioning schemes available in CSS, including static, relative, absolute, and fixed positioning. Each positioning scheme offers different ways to position elements within the document flow.

  1. Static Positioning: The default positioning scheme in CSS. Elements with static positioning are placed in the normal flow of the document and are not affected by other positioning properties. This is the default behavior unless overridden.

  2. Relative Positioning: Allows you to move an element relative to its normal position in the document flow. It doesn’t affect the position of other elements. The element’s original space is preserved, and other elements are not adjusted to fill the space.

  3. Absolute Positioning: Allows you to position an element relative to its nearest positioned ancestor or the document’s initial containing block. It takes the element out of the normal document flow, and other elements are positioned as if the absolute positioned element does not exist.

  4. Fixed Positioning: Positions an element relative to the browser window, regardless of scrolling. The element remains fixed even when the page is scrolled. It is often used for elements like headers, footers, or sidebars that should remain visible at all times.

Figure 1.Four types of CSS positioning.

For a live demo, see the following link.

CSS floats

CSS floats are a positioning property used to float an element to the left or right of its containing block, allowing text and other elements to wrap around it. Floats are commonly used for creating multi-column layouts, positioning images within text, and creating responsive designs.

Figure 2.Usgae of CSS float.

To use floats, you can apply the float property to an element and specify either left or right as the value.

<style>
  .float-left {
    float: left;
    width: 200px;
    margin-right: 20px;
  }

  .float-right {
    float: right;
    width: 200px;
    margin-left: 20px;
  }
</style>

<div class="float-left">
  <img src="image1.jpg" alt="Image 1">
  <p>Left floated image with some text...</p>
</div>

<div class="float-right">
  <img src="image2.jpg" alt="Image 2">
  <p>Right floated image with some text...</p>
</div>

In modern web development, CSS floats are being replaced by more robust layout techniques like flexbox and CSS grid.

CSS flexbox

CSS flexbox provides a “flexible” way to align and distribute space among items in a container. It simplifies the process of creating responsive and dynamic layouts, allowing you to control the alignment, order, and size of elements within a container. The CSS flexbox makes it easier to design flexible responsive layout structure without using float or positioning.

  • You can create a flex container by using display: flex.
  • Use justify-content: center to horizontally center the flex items within the container.
  • Use align-items: center to vertially center the flex items within the container.
  • Use flex-direciton: row or flex-direction: column to set the direction of the flex items.
<style>
  .flex-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
  }

  .flex-item {
    flex: 1;
    margin: 10px;
    text-align: center;
  }
</style>

<div class="flex-container">
  <div class="flex-item">Item 1</div>
  <div class="flex-item">Item 2</div>
  <div class="flex-item">Item 3</div>
</div>

For more information on the flexbox, follow the link.


Full Stack Software Engineering for Beginners

July 7th, 2023


Introduction to JavaScript: variables, data types, and operators

Javascript

JavaScript is a versatile and widely used programming language that allows developers to add interactivity, behavior, and dynamic elements to websites and web applications. Initially designed as a client-side scripting language, JavaScript has evolved to become a powerful, multi-paradigm language capable of running on both the client side (in web browsers) and the server side (with the help of platforms like Node.js). JavaScript’s primary purpose is to enable developers to create interactive web pages by manipulating the Document Object Model (DOM) and responding to user actions. It offers a rich set of features, including support for variables, data types, operators, functions, control flow statements, and extensive libraries and frameworks. JavaScript’s flexibility, widespread adoption, and extensive ecosystem make it an essential language for modern web development, empowering developers to build dynamic and engaging web experiences.

Variables

Definition and Purpose

Variables in JavaScript are used to store and manipulate data. They provide a way to store values that can be accessed and modified throughout the program. Variables serve as containers that hold different types of information, such as numbers, text, or objects. By using variables, we can store and retrieve data dynamically, making our programs more flexible and interactive.

Variable Declaration

In JavaScript, variables are declared using the let, const, or var keywords. The let and const keywords were introduced in modern JavaScript and are preferred over var. When declaring a variable, we specify its name, which can be any valid identifier, following certain naming conventions.

Variable Assignment

After declaring a variable, we can assign a value to it using the assignment operator =. This assigns the specified value to the variable, allowing us to store and retrieve it later in the program. Variables can be assigned initial values at the time of declaration or assigned new values later on.

Variable Naming Conventions

When naming variables, it’s important to follow certain conventions to ensure code readability and maintainability. JavaScript variable names are case-sensitive and can consist of letters, digits, underscores, or dollar signs. It’s recommended to use descriptive names that reflect the purpose of the variable and follow camel case or snake case conventions.

Example: Declaring and Assigning Variables

// Declaring variables
let firstName;
let age;

// Assigning values to variables
firstName = "John";
age = 25;

// Outputting variables
console.log("Name: " + firstName);
console.log("Age: " + age);

Example: Variable Naming Conventions

let myVariable = 10; // Camel case
const PI_VALUE = 3.14; // Uppercase with underscores

Data Types

In JavaScript, data types can be classified into primitive and complex types.

Primitive Data Types

Primitive data types are the most basic building blocks and include numbers, strings, booleans, null, and undefined. They represent simple values and are immutable.

Complex Data Types

Complex data types are composed of multiple values and can be dynamically modified. The two main complex data types in JavaScript are objects and arrays. Objects are used to represent collections of related data, while arrays are used to store multiple values in an ordered manner.

Example: Primitive Data Types

let numberValue = 42; // Number
let stringValue = "Hello, world!"; // String
let booleanValue = true; // Boolean
let nullValue = null; // Null
let undefinedValue = undefined; // Undefined

Example: Complex Data Types

let person = {
  firstName: "John",
  lastName: "Doe",
  age: 30
}; // Object

let fruits = ["apple", "banana", "orange"]; // Array

Operators

Arithmetic Operators

Arithmetic operators perform mathematical calculations on numeric values. They include addition (+), subtraction (-), multiplication (*), division (/), and modulo (%) operators.

Comparison Operators

Comparison operators are used to compare values and return a boolean result. They include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=) operators.

Assignment Operators

Assignment operators are used to assign values to variables. They include the basic assignment (=) operator, as well as compound assignment operators such as addition assignment (+=), subtraction assignment (-=), multiplication assignment (*=), division assignment (/=), and modulo assignment (%=).

Examples: Arithmetic Operators

let num1 = 10;
let num2 = 5;

let sum = num1 + num2; // Addition
let difference = num1 - num2; // Subtraction
let product = num1 * num2; // Multiplication
let quotient = num1 / num2; // Division
let remainder = num1 % num2; // Modulo

Examples: Comparison Operators

let x = 5;
let y = 10;

console.log(x == y); // false
console.log(x != y); // true
console.log(x > y); // false
console.log(x < y); // true
console.log(x >= y); // false
console.log(x <= y); // true

Examples: Assignment Operators

let a = 10;

a += 5; // Equivalent to: a = a + 5;
a -= 3; // Equivalent to: a = a - 3;
a *= 2; // Equivalent to: a = a * 2;
a /= 4; // Equivalent to: a = a / 4;
a %= 2; // Equivalent to: a = a % 2;

Manipulating the DOM with JavaScript

Introduction to DOM Manipulation

Definition and Purpose

The Document Object Model (DOM) represents the structure of an HTML document as a tree-like structure. DOM manipulation refers to the process of programmatically accessing and modifying elements, attributes, and content of an HTML document using JavaScript. By manipulating the DOM, we can dynamically update the appearance and behavior of web pages, respond to user interactions, and create interactive and engaging web experiences.

Accessing DOM Elements

JavaScript provides several methods to access DOM elements, including getElementById, getElementsByClassName, getElementsByTagName, and querySelector. These methods allow us to target specific elements on the web page based on their IDs, classes, tags, or CSS selectors.

Modifying DOM Elements

Once we have accessed DOM elements, we can modify their properties, attributes, or content using JavaScript. Common manipulations include changing text or HTML content, modifying CSS styles, adding or removing classes, and manipulating attributes like src, href, or value.

Examples

Example 1 demonstrates accessing and modifying DOM elements using the getElementById and textContent properties to change the text content of an element. Example 2 showcases modifying CSS styles by manipulating the classList property to add or remove classes dynamically.

Example 1:

// Accessing an element by ID and modifying its content
let heading = document.getElementById("myHeading");
heading.textContent = "Hello, JavaScript!";

Example 2:

// Accessing an element by class name and modifying its style
let elements = document.getElementsByClassName("myClass");
for (let i = 0; i < elements.length; i++) {
    elements[i].style.color = "red";
}

Event Handling

Introduction to Events

Events are actions or occurrences that happen in the browser, such as a user clicking a button, hovering over an element, or submitting a form. JavaScript allows us to respond to these events and execute code in response.

Event Listeners

Event listeners are functions that listen for specific events on DOM elements and execute a specified code block when the event occurs. By attaching event listeners to elements, we can create interactive functionality in our web pages.

Event Propagation and Event Object

Understanding event propagation, which includes capturing and bubbling phases, allows us to control how events are handled when multiple elements are involved. Additionally, event objects provide information about the event and its target element, enabling us to access relevant data.

Examples

Example 1:

// Adding a click event listener to a button
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
  console.log("Button clicked!");
});

Example 2:

// Event propagation and accessing event target
let parent = document.getElementById("parentElement");
let child = document.getElementById("childElement");

parent.addEventListener("click", function(event) {
  console.log("Parent clicked!");
  event.stopPropagation();
});

child.addEventListener("click", function(event) {
  console.log("Child clicked!");
});

Creating and Modifying Elements

Creating Elements

JavaScript allows us to create new elements dynamically and insert them into the DOM. We can use methods like createElement and appendChild to generate new elements and add them as children to existing elements.

Modifying Elements

We can also modify existing elements by adding or removing attributes, properties, or content. Methods like setAttribute, removeAttribute, and innerHTML enable us to manipulate elements according to our needs.

Examples

Example 1 demonstrates creating a new paragraph element and appending it to an existing div element. Example 2 showcases modifying an existing element’s attributes using setAttribute and manipulating its content using innerHTML.

Example 1:

// Creating a new paragraph element and appending it to an existing div element
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph!";
let parentElement = document.getElementById("parentElement");
parentElement.appendChild(newParagraph);

Example 2:

// Modifying an existing element's attributes and content
let link = document.getElementById("myLink");
link.setAttribute("href", "https://www.example.com");
link.innerHTML = "Click me!";

Sample HTML: Manipulating the DOM with JavaScript

<!DOCTYPE html>
<html>
<head>
   <title>DOM Manipulation with JavaScript</title>
   <style>
      .myClass {
         font-weight: bold;
      }
   </style>
</head>
<body>
   <h1 id="myHeading">Original Heading</h1>
   <button id="myButton">Click Me</button>
   <div id="parentElement">
      <p id="childElement">Click me too!</p>
   </div>
   <a id="myLink" href="#">Link</a>

   <script>
      // Example 1: Accessing and modifying DOM elements
      let heading = document.getElementById("myHeading");
      heading.textContent = "Hello, JavaScript!";

      let elements = document.getElementsByClassName("myClass");
      for (let i = 0; i < elements.length; i++) {
         elements[i].style.color = "red";
      }

      // Example 2: Event handling
      let button = document.getElementById("myButton");
      button.addEventListener("click", function() {
         console.log("Button clicked!");
      });

      let parent = document.getElementById("parentElement");
      let child = document.getElementById("childElement");

      parent.addEventListener("click", function(event) {
         console.log("Parent clicked!");
         event.stopPropagation();
      });

      child.addEventListener("click", function(event) {
         console.log("Child clicked!");
      });

      // Example 3: Creating and modifying elements
      let newParagraph = document.createElement("p");
      newParagraph.textContent = "This is a new paragraph!";
      let parentElement = document.getElementById("parentElement");
      parentElement.appendChild(newParagraph);

      let link = document.getElementById("myLink");
      link.setAttribute("href", "https://www.example.com");
      link.innerHTML = "Click me!";
   </script>
</body>
</html>