Se connecterS'abonner

Chapitre 16

Apply common technologies, for web development

Lecture : 10 minQuiz de 12 questions

# Apply common technologies, for web development ## Objectifs et prérequis This chapter aims to equip Upper Sixth ICT students with the practical skills to apply common technologies in web development, specifically focusing on styling web pages using CSS and creating interactive web pages using JavaScript. Students will learn to structure, style, and enhance web content to meet functional and aesthetic requirements, preparing them for further studies or entry-level roles in web development. Prerequisites include foundational knowledge of HTML5 structure, basic file management, and familiarity with using a text editor and web browser for testing code. Students should be able to write valid HTML5 documents before proceeding. ## Introduction Web development relies on three core technologies: HTML for structure, CSS for presentation, and JavaScript for behavior. This chapter builds directly on prior HTML knowledge to teach how CSS controls the visual layout and styling of web pages, and how JavaScript enables dynamic, user-responsive interactions. In the Cameroonian and broader African context, where digital inclusion and local content creation are growing priorities—such as in e-government services, educational platforms, and small business websites—mastering these technologies empowers students to develop accessible, culturally relevant web solutions. The focus is on standards-compliant, maintainable code that works across devices and browsers, aligning with global best practices while addressing local needs like low-bandwidth optimization and multilingual support. ## I. Styling Web Pages with CSS ### Context and Definition Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document written in HTML or XML. Developed by the W3C in 1996, CSS separates content from design, enabling consistent styling across multiple pages and facilitating responsive design. In Cameroon, where mobile internet usage dominates (over 70% of users access the web via smartphones per 2023 ARTC data), CSS is essential for creating mobile-friendly interfaces for local services like AgriMarket platforms or university portals. > CSS is a rule-based language where styles are applied to HTML elements through selectors and declaration blocks. ### Core Concepts CSS operates on the principle of cascading and inheritance. Styles can be applied via inline, internal (embedded), or external methods. External stylesheets are preferred for maintainability and reusability. The box model—comprising content, padding, border, and margin—is fundamental to layout. Selectors target HTML elements: type (e.g., `p`), class (`.classname`), ID (`#id`), attribute, and pseudo-classes (e.g., `:hover`). Specificity determines which style applies when conflicts arise: inline > ID > class/attribute/pseudo-class > type. ### Key Properties and Values - **Typography**: `font-family`, `font-size`, `font-weight`, `text-align`, `line-height`, `color`. Example: `font-family: 'Arial', sans-serif;` ensures fallback readability on systems lacking specific fonts. - **Layout**: `display` (block, inline, inline-block, flex, grid), `width`, `height`, `max-width`, `margin`, `padding`. Flexbox and CSS Grid are modern layout models; Flexbox suits one-dimensional layouts (e.g., navigation bars), Grid for two-dimensional (e.g., photo galleries). - **Visual Effects**: `background-color`, `background-image`, `border`, `border-radius`, `box-shadow`, `opacity`. Example: `border-radius: 8px;` creates soft corners common in modern African fintech app UIs. - **Responsive Design**: `@media` queries adapt styles to screen size. Example: `@media (max-width: 600px) { .container { width: 100%; } }` ensures content flows on small screens. ### Vocabulary to Retain - Selector: Pattern used to select HTML elements for styling. - Declaration: Property-value pair inside a CSS rule (e.g., `color: blue;`). - Specificity: Weight assigned to a selector that determines precedence in cascade. - Box Model: Rectangular layout model comprising content, padding, border, margin. - Media Query: CSS technique to apply styles based on device characteristics (width, height, orientation). - Flexbox: One-dimensional layout model for distributing space and aligning items in a container. ### Concrete Examples (Cameroonian/African Context) - A student designs a website for a Yaoundé-based cooperative selling cassava flour. Using CSS, they set a warm earth-tone palette (`#8B4513`, `#DEB887`) and use Flexbox to align product images responsively on mobile. - For an educational portal serving rural schools in the East Region, CSS Grid creates a dashboard where lesson cards rearrange from a 3-column layout on desktop to a single column on phones, improving accessibility on low-end devices. - A Douala startup’s job board uses `:hover` effects on buttons (`background-color: #0066cc; color: white;`) to provide tactile feedback, increasing user engagement on touchscreens. ### Exam-Style Question and Plan **Question**: Explain how CSS can be used to create a responsive navigation bar that collapses into a hamburger menu on screens narrower than 768px. Include the roles of media queries, Flexbox, and pseudo-classes in your answer. Provide a brief code outline. **Plan**: 1. Introduction: Define responsive navigation and its importance for mobile users in Cameroon. 2. Base Styling: Use Flexbox (`display: flex; justify-content: space-between;`) to align logo and links horizontally on large screens. 3. Media Query: `@media (max-width: 768px)` to hide horizontal links and show hamburger icon. 4. Hamburger Menu: Style the icon (e.g., three stacked lines using `::before`/`::after` pseudo-elements) and position it absolutely. 5. Interaction: Use `:hover` and `:active` pseudo-classes on the icon for feedback; note that full toggle requires JavaScript (beyond CSS alone). 6. Conclusion: Emphasize CSS’s role in layout and visual state; JavaScript handles the toggle mechanism. ## II. Creating Interactive Web Pages with JavaScript ### Context and Definition JavaScript is a high-level, interpreted programming language that enables dynamic behavior in web pages. First released by Netscape in 1995, it is now standardized as ECMAScript (ECMA-262). JavaScript runs in the browser’s engine (e.g., V8 in Chrome) and manipulates the Document Object Model (DOM) to update content, control multimedia, animate images, and respond to user actions without reloading the page. In Cameroon, where interactive e-learning and m-health applications are expanding—such as the MTN-backed mHealth initiative for maternal care—JavaScript is vital for creating engaging, real-time user experiences. > JavaScript is a client-side scripting language that adds interactivity and dynamic content to web pages by interacting with the HTML DOM. ### Core Concepts JavaScript interacts with the web page through the DOM, a tree-like representation of HTML elements. Scripts can be embedded internally (`<script>`) or linked externally (`.js` file). Key concepts include variables (using `let`, `const`, `var`), data types (string, number, boolean, object, array), operators, control structures (if/else, loops), functions, and event handling. The DOM provides methods like `getElementById()`, `querySelector()`, `createElement()`, and properties like `innerHTML`, `textContent`, `style`. Events (e.g., `click`, `keydown`, `submit`) trigger functions via event listeners (`addEventListener()`). ### Syntax and Structure - **Variables**: `let userName = "Aminata";` (block-scoped, reusable); `const PI = 3.14;` (block-scoped, constant). - **Data Types**: Strings (`"Hello"`), numbers (`42`), booleans (`true`/`false`), objects (`{name: "Jean", age: 20}`), arrays (`[1, 2, 3]`). - **Control Flow**: ```javascript if (score >= 50) { result = "Pass"; } else { result = "Fail"; } ``` Loops: `for`, `while`, `forEach` (for arrays). - **Functions**: Reusable blocks. ```javascript function calculateTotal(price, tax) { return price + (price * tax / 100); } ``` Arrow functions (ES6): `const add = (a, b) => a + b;` ### Event Handling and DOM Manipulation Events are actions detected by the browser. Common events: - `click`: Mouse button pressed. - `input`: Value of an `<input>` or `<textarea>` changes. - `submit`: Form is submitted. - `load`: Page finishes loading. - `keydown`: Key is pressed. Example: ```javascript document.getElementById("btnSubmit").addEventListener("click", function() { let name = document.getElementById("txtName").value; alert("Hello, " + name + "!"); }); ``` This retrieves user input and displays a greeting without page reload. ### Vocabulary to Retain - DOM (Document Object Model): Programming interface for HTML/XML documents representing the page as nodes and objects. - Event Listener: Procedure that waits for an event to occur and executes a function in response. - Callback Function: Function passed as an argument to another function, to be executed later. - Scope: Region of code where a variable is accessible (`let`/`const`: block scope; `var`: function scope). - Asynchronous JavaScript: Operations that do not block execution (e.g., `setTimeout`, `fetch API`). - JSON (JavaScript Object Notation): Lightweight data-interchange format, easy for humans to read/write and machines to parse/generate. ### Concrete Examples (Cameroonian/African Context) - A Yaoundé university’s online registration system uses JavaScript to validate form fields in real time: checking if a student ID is 8 digits (`/^\d{8}$/.test(id)`) and showing an error message via `element.textContent = "Invalid ID"` if not, reducing server load and improving UX. - In an agricultural SMS gateway simulator for farmers in the North Region, JavaScript processes user input (crop type, field size) to calculate fertilizer needs using a formula, then displays results dynamically without refreshing the page. - A Cameroonian news site uses JavaScript to implement infinite scroll: as the user nears the bottom of the page, `window.addEventListener("scroll", ...)` triggers an AJAX-like fetch (via `fetch()`) to load more articles, mimicking platforms like BBC Africa Mobile. ### Exam-Style Question and Plan **Question**: Describe how JavaScript can be used to validate a user registration form before submission, ensuring that the password field contains at least 8 characters, includes one uppercase letter, and matches the confirmation password field. Include DOM access, event handling, and conditional logic in your explanation. **Plan**: 1. Introduction: Explain client-side validation benefits (reduced server load, instant feedback) for Cameroonian users on variable bandwidth. 2. DOM Access: Use `document.getElementById()` or `querySelector()` to reference password (`#pwd`), confirm password (`#cpwd`), and submit button (`#btnSubmit`). 3. Event Listener: Attach `submit` event to the form (`form.addEventListener("submit", function(e) {...})`) to intercept submission. 4. Validation Logic: - Retrieve values: `let pwd = document.getElementById("pwd").value;` - Check length: `if (pwd.length < 8) { error = "Too short"; }` - Check uppercase: `if (!/[A-Z]/.test(pwd)) { error = "Needs uppercase"; }` - Check match: `if (pwd !== document.getElementById("cpwd").value) { error = "Passwords mismatch"; }` 5. Feedback and Prevention: - Display error in a `<span id="error">` via `textContent`. - If invalid, call `e.preventDefault()` to stop form submission. - If valid, allow submission (or clear error message). 6. Conclusion: Emphasize that this improves usability and accessibility, especially on low-cost Android devices common in Cameroonian schools. ## Synthèse du chapitre - CSS controls the visual presentation of HTML content through selectors, properties, and values, enabling responsive and accessible design critical for mobile-first contexts in Cameroon and Africa. - JavaScript adds dynamic behavior by manipulating the DOM and responding to events, allowing real-time validation, content updates, and user engagement without page reloads. - Together, HTML, CSS, and JavaScript form the frontend triad essential for modern web development, with CSS handling layout and style, and JavaScript managing interactivity and logic. - Best practices include external stylesheets for maintainability, semantic HTML for accessibility, unobtrusive JavaScript (separating behavior from structure), and progressive enhancement to ensure basic functionality works even if CSS/JS fail. - In Cameroonian educational and entrepreneurial projects—such as e-learning platforms, agri-tech tools, or civic portals—applying these technologies enables locally relevant, user-centered solutions that bridge digital divides. - Mastery of specificity, the box model, Flexbox/Grid, DOM methods, event handling, and basic data validation is essential for success in practical assessments and real-world web development tasks. ## Glossaire - **Cascading Style Sheets (CSS)**: Stylesheet language used to describe the presentation of a document written in HTML or XML. - **Box Model**: Rectangular model comprising content, padding, border, and margin that defines element size and spacing. - **Flexbox**: One-dimensional CSS layout model for aligning and distributing space among items in a container. - **Grid Layout**: Two-dimensional CSS layout system for creating complex row-and-column designs. - **Media Query**: CSS technique to apply styles based on device characteristics like screen width, height, or orientation. - **Document Object Model (DOM)**: Programming interface representing HTML/XML documents as a tree of nodes accessible via JavaScript. - **Event Listener**: Function that waits for a specific event (e.g., click, keypress) to execute in response. - **Callback Function**: Function passed as an argument to another function to be executed after an operation completes. - **Specificity**: Algorithm that determines which CSS rule applies when multiple rules target the same element. - **JSON (JavaScript Object Notation)**: Lightweight data-interchange format based on JavaScript object syntax, used for data transmission. - **let/const**: Block-scoped variable declarations in JavaScript (`let` for reassignment, `const` for constants). - **Pseudo-class**: Keyword added to a selector to specify a special state of an element (e.g., `:hover`, `:focus`).

Quiz du chapitre

12 questions — vérifie chaque réponse pour voir l'explication.

  1. 1. Which HTML tag is used to define the main content of a document, distinct from headers, footers, and navigation?
  2. 2. In CSS, what does the property 'box-sizing: border-box;' do?
  3. 3. Which JavaScript method is used to select the first element that matches a specified CSS selector?
  4. 4. What is the correct way to link an external CSS file named 'styles.css' in the head of an HTML document?
  5. 5. A student wants to create a responsive image that scales down but never exceeds its original size. Which CSS rule should they apply?
  6. 6. In a form, which attribute is required for an <input> element to be successfully submitted with its value?
  7. 7. Which of the following best describes the purpose of the 'alt' attribute in an <img> tag?
  8. 8. A developer writes the following CSS: .box { width: 200px; padding: 20px; border: 5px solid black; }. If box-sizing is set to content-box, what is the total rendered width of the element?
  9. 9. Which HTTP status code indicates that the server understood the request but refuses to authorize it?
  10. 10. In JavaScript, what is the output of the following code: console.log(typeof NaN);
  11. 11. Which of the following statements about CSS Flexbox is FALSE?
  12. 12. Consider this HTML snippet: <button onclick="alert('Hello')">Click me</button>. What is the most significant accessibility issue with this implementation?