โ† Introduction to HTML Level Three ยท Lesson 3 of 8

Module Two

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
1

Course Outline

Course Outline: Introduction to HTML Level Three

๐Ÿš€ Introduction to HTML โ€” Level Three

Prerequisites HTML Level One & Level Two (or equivalent knowledge) โฑ 8โ€“10 weeks • 1โ€“2 sessions/week Advanced Level

Take your HTML skills to the professional level. Learn structured data, Canvas, Web Components, SVG, and advanced accessibility.

๐Ÿ“– Course Overview

Introduction to HTML โ€“ Level Three is the final and most advanced level of our HTML series. This course is designed for students who have completed Level One and Level Two and are ready to learn professional-grade HTML techniques.

In this course, you will go beyond the basics and learn how to build smarter, more interactive, and more powerful web pages. You will learn how to help search engines understand your content with structured data. You will create graphics and animations using the Canvas API. You will build custom HTML tags with Web Components. You will work with SVG for scalable graphics. And you will master advanced accessibility and performance techniques.

By the end of this course, you will be able to build websites that are professional, interactive, and inclusive โ€“ just like the ones built by developers at top tech companies.

๐Ÿ“š Prerequisites

Before starting Level Three, you should be comfortable with everything taught in Level One and Level Two. Specifically, you should know:

  • How to write HTML tags and attributes.
  • The HTML5 boilerplate.
  • Semantic elements โ€“ <header>, <nav>, <main>, <article>, <aside>, <footer>.
  • Advanced text structuring โ€“ <figure>, <details>, <summary>, <em>, <strong>, <blockquote>, <cite>.
  • Hyperlinks โ€“ absolute vs relative paths, target="_blank", mailto:, tel:.
  • Media โ€“ <picture>, srcset, loading="lazy", <video>, <audio>, <iframe>.
  • Forms โ€“ <label>, <fieldset>, input types (email, tel, number, date), <select>, <textarea>, required, pattern.
  • Tables โ€“ <thead>, <tbody>, <tfoot>, colspan, rowspan, scope.
  • Basic accessibility and SEO โ€“ ARIA landmarks, heading hierarchy, lang attribute.
๐Ÿ’ก Tip: If you are not confident in any of these areas, review the Level Two modules before starting Level Three. A strong foundation is key!

๐Ÿ—บ๏ธ Course Structure

Level Three is divided into 8 modules. Each module builds on the previous one and introduces a new advanced topic. The course is designed to be completed in 8โ€“10 weeks if you study regularly (1โ€“2 sessions per week).

Module Topic What You Will Learn Project
1 Structured Data & Microdata How to add Schema.org markup to help search engines understand your content. Recipe page with rich results
2 Advanced HTML5 APIs โ€“ Canvas How to draw graphics, shapes, and animations using JavaScript. Drawing app / Chart builder
3 Advanced HTML5 APIs โ€“ Drag and Drop How to make elements draggable and droppable for interactive UIs. Drag-and-drop todo list
4 Web Components & Custom Elements How to create your own custom HTML tags with JavaScript. Custom web component library
5 HTML Templates & Slots How to reuse HTML efficiently with <template> and <slot>. Template-based gallery
6 Advanced Forms & Inputs Using <datalist>, inputmode, autocomplete, and more. Advanced contact form
7 SVG โ€“ Scalable Vector Graphics How to add crisp, scalable graphics that never get blurry. Scalable logo & icons
8 Performance & Advanced Accessibility Making your site lightning-fast and truly inclusive. High-performance accessible website

๐Ÿ“‹ Detailed Module Outline

Module 1: Structured Data & Microdata

Objective: Learn how to use Schema.org vocabulary to add structured data to your HTML, helping search engines understand your content better.

  • Lesson 1: What is structured data and why it matters for SEO.
  • Lesson 2: Introduction to Schema.org and its vocabulary.
  • Lesson 3: Using microdata attributes โ€“ itemscope, itemtype, itemprop.
  • Lesson 4: Marking up People, Organisations, and Products.
  • Lesson 5: Marking up Recipes, Events, and Reviews.
  • Lesson 6: Testing your structured data with Google's Rich Results Test.
๐Ÿงช Practical Lab: Add structured data to a recipe page and test it with Google's Rich Results Test.

Module 2: Advanced HTML5 APIs โ€“ Canvas

Objective: Learn how to use the <canvas> element to draw graphics, shapes, and animations.

  • Lesson 1: Introduction to the Canvas API.
  • Lesson 2: Drawing rectangles, lines, and circles.
  • Lesson 3: Working with colours, gradients, and styles.
  • Lesson 4: Drawing text and images on the canvas.
  • Lesson 5: Creating simple animations.
  • Lesson 6: Building a drawing app or a simple chart.
๐Ÿงช Practical Lab: Build a drawing app where users can click and drag to draw shapes.

Module 3: Advanced HTML5 APIs โ€“ Drag and Drop

Objective: Learn how to make elements draggable and droppable for interactive user interfaces.

  • Lesson 1: Introduction to the Drag and Drop API.
  • Lesson 2: Making elements draggable with draggable.
  • Lesson 3: Handling drag events โ€“ dragstart, dragend.
  • Lesson 4: Handling drop events โ€“ dragover, drop.
  • Lesson 5: Dragging and dropping files.
  • Lesson 6: Building a drag-and-drop todo list.
๐Ÿงช Practical Lab: Build a todo list where tasks can be dragged and dropped to reorder them.

Module 4: Web Components & Custom Elements

Objective: Learn how to create your own custom HTML tags using Web Components.

  • Lesson 1: What are Web Components and why they matter.
  • Lesson 2: Creating a custom element with class and customElements.define().
  • Lesson 3: Adding a shadow DOM for encapsulation.
  • Lesson 4: Using templates inside custom elements.
  • Lesson 5: Adding attributes and properties to custom elements.
  • Lesson 6: Building a library of reusable web components.
๐Ÿงช Practical Lab: Create a <fancy-card> custom element that can be reused across a website.

Module 5: HTML Templates & Slots

Objective: Learn how to reuse HTML code efficiently with <template> and <slot>.

  • Lesson 1: Introduction to <template> โ€“ writing HTML that is not displayed until used.
  • Lesson 2: Using <template> with JavaScript to clone content.
  • Lesson 3: Introduction to <slot> โ€“ creating placeholders inside components.
  • Lesson 4: Using named slots for different content.
  • Lesson 5: Building a template-based gallery.
๐Ÿงช Practical Lab: Build a photo gallery that uses <template> to generate image cards dynamically.

Module 6: Advanced Forms & Inputs

Objective: Learn advanced form techniques to build smarter, more user-friendly forms.

  • Lesson 1: Using <datalist> for autocomplete suggestions.
  • Lesson 2: Using inputmode to control mobile keyboards.
  • Lesson 3: Using autocomplete to help browsers auto-fill forms.
  • Lesson 4: Using form attributes to link inputs outside the <form>.
  • Lesson 5: Using novalidate to turn off browser validation.
  • Lesson 6: Building an advanced contact form with all these features.
๐Ÿงช Practical Lab: Build a contact form with autocomplete, inputmode, and datalist suggestions.

Module 7: SVG โ€“ Scalable Vector Graphics

Objective: Learn how to use SVG to add crisp, scalable graphics to your web pages.

  • Lesson 1: What is SVG and why it is better than raster images.
  • Lesson 2: Drawing basic shapes โ€“ rectangles, circles, lines, and paths.
  • Lesson 3: Adding colours, gradients, and text.
  • Lesson 4: Using SVG for icons and logos.
  • Lesson 5: Animating SVG with CSS.
  • Lesson 6: Building a scalable logo and icon set.
๐Ÿงช Practical Lab: Create an SVG logo that scales perfectly on any screen size.

Module 8: Performance & Advanced Accessibility

Objective: Learn how to make your websites lightning-fast and truly inclusive for everyone.

  • Lesson 1: Performance optimisation โ€“ minification, compression, and CDNs.
  • Lesson 2: Lazy loading and deferring scripts.
  • Lesson 3: Advanced accessibility โ€“ ARIA roles, states, and properties.
  • Lesson 4: Focus management and keyboard navigation.
  • Lesson 5: Live regions for dynamic content.
  • Lesson 6: Testing with real users and accessibility tools.
๐Ÿงช Practical Lab: Optimise a website to score 100 on Lighthouse for Performance, Accessibility, SEO, and Best Practices.

๐Ÿ› ๏ธ Final Project

Portfolio Website with Advanced Features

Project Brief: Build a professional portfolio website that showcases everything you have learned in Level Three. Your website must include:

  • โœ… Structured Data: Mark up your portfolio items using Schema.org.
  • โœ… Canvas: Create an interactive chart or drawing element.
  • โœ… Drag and Drop: Allow users to reorder items in your portfolio.
  • โœ… Web Component: Create at least one custom element (like <project-card>).
  • โœ… Templates: Use <template> to generate dynamic content.
  • โœ… Advanced Form: A contact form with autocomplete and datalist.
  • โœ… SVG: Use SVG for your logo and icons.
  • โœ… Performance & Accessibility: Your site must score at least 95 on Lighthouse.

Submission: Submit your HTML files, along with a short report on how you implemented each feature.

๐Ÿ“Š Assessment Criteria

๐Ÿ“ Weekly Quizzes 15%
๐Ÿงช Practical Labs 25%
๐Ÿ“‹ Assignments 25%
๐Ÿš€ Final Project 35%

๐Ÿ› ๏ธ Tools & Resources

๐Ÿ”‘ Key Takeaways

  • 1. Structured data helps search engines understand your content and can improve your search ranking.
  • 2. The Canvas API lets you draw graphics, charts, and animations directly in the browser.
  • 3. The Drag and Drop API makes it easy to build interactive interfaces.
  • 4. Web Components let you create reusable custom HTML tags.
  • 5. <template> and <slot> help you reuse HTML code efficiently.
  • 6. Advanced form techniques like <datalist> and autocomplete make forms smarter.
  • 7. SVG provides crisp, scalable graphics that never get blurry.
  • 8. Performance optimisation and advanced accessibility make your website fast and inclusive.

๐Ÿ’ฌ Classroom Discussion Questions

  • 1. How can structured data help a small business website attract more customers?
  • 2. What are some real-world applications of the Canvas API?
  • 3. How would you use drag and drop to improve user experience on a website?
  • 4. Why are Web Components considered a powerful tool for developers?
  • 5. How can you ensure your website is accessible to people with disabilities?

โ“ Frequently Asked Questions

  • Q1: Do I need to know JavaScript for Level Three?
    A: Some modules (Canvas, Drag and Drop, Web Components) use JavaScript. You will learn the basics as you go, but it helps to have some knowledge.
  • Q2: How long will Level Three take?
    A: Approximately 8โ€“10 weeks if you study 1โ€“2 sessions per week.
  • Q3: Can I skip modules I already know?
    A: Yes, if you are already comfortable with a topic, you can skip ahead. However, we recommend reviewing the material anyway.
  • Q4: What is the most important skill I will learn?
    A: How to think like a professional developer โ€“ solving problems, writing clean code, and building inclusive, performant websites.
  • Q5: What comes after Level Three?
    A: After Level Three, you can move on to CSS and JavaScript in more depth, or start building full-stack web applications.

๐Ÿ“Œ Introduction to HTML โ€“ Level Three • Advanced course for young web developers.
Build professional, interactive, and inclusive websites with cutting-edge HTML techniques.

<structured-data> <canvas> <web-components> <svg> <performance> <accessibility>

2

Module One

Module 1: Structured Data & Microdata

๐Ÿ” Module 1: Structured Data & Microdata

Helping search engines understand your content like never before!

๐Ÿ“– Module Introduction

Welcome to Module 1 of your HTML Level Three journey! In Level One and Level Two, you learned how to build beautiful, semantic, and accessible web pages. You learned about the HTML5 boilerplate, semantic tags, forms, tables, media, and more. You are now an intermediate web developer.

Now, in Level Three, we are going to take your skills to the professional level. And we start with one of the most important topics for modern web development: Structured Data and Microdata.

Have you ever searched for a recipe on Google and seen a result that shows the cooking time, the rating, and a picture โ€“ all right there in the search results? That is structured data at work! It makes your website stand out and helps people find exactly what they need.

In this module, you will learn:

  • What structured data is and why it matters.
  • How to use Schema.org โ€“ the vocabulary for structured data.
  • How to add microdata to your HTML using itemscope, itemtype, and itemprop.
  • How to mark up different types of content โ€“ like people, products, recipes, events, and reviews.
  • How to test your structured data using Google's Rich Results Test.

Think of this module as giving your website a superpower. By the end, you will be able to make your website stand out in search results and help people find your content more easily. Let us begin!

๐ŸŽฏ Learning Objectives

By the end of this module, you will be able to:

  • Explain what structured data is and why it is important for SEO.
  • Understand the Schema.org vocabulary and how to use it.
  • Use microdata attributes โ€“ itemscope, itemtype, and itemprop.
  • Mark up different types of content โ€“ People, Organisations, Products, Recipes, Events, and Reviews.
  • Test your structured data using Google's Rich Results Test.
  • Understand the difference between microdata, RDFa, and JSON-LD.
  • Apply structured data to your own projects.

๐Ÿ“š Warm-up Story: Chidiโ€™s Recipe Blog

Chidi was a 13-year-old boy who loved cooking. He had a blog where he shared his favourite Nigerian recipes โ€“ Jollof rice, Egusi soup, and Suya. He wrote amazing content with beautiful pictures and clear instructions. His blog was perfect โ€“ or so he thought.

One day, Chidi noticed that his blog posts were not appearing on Google the way he wanted. When he searched for โ€œJollof rice recipe,โ€ other blogs appeared with pictures, ratings, and cooking times right in the search results. His blog just showed a plain blue link.

Chidi was frustrated. He asked his big sister, who was a web developer, for help. She said, โ€œChidi, you need to add structured data to your blog. It tells Google what your content is about โ€“ like the ingredients, the cooking time, and the rating. Without it, Google does not know that your page is a recipe.โ€

Chidi learned how to use Schema.org and microdata to mark up his recipes. A week later, his blog appeared on Google with pictures, ratings, and cooking times. His visitors tripled!

In this module, you will learn exactly what Chidi learned. You will learn how to help search engines understand your content and make your website stand out in search results. Let us get started!

๐Ÿงฉ Main Lessons

Lesson 1: What is Structured Data?

Definition: Structured data is a way of organising information on your website so that search engines can understand it more easily. It is like labelling your content.

Why important: It helps search engines display your content in rich results โ€“ with pictures, ratings, prices, and more โ€“ which makes your website more attractive to users.

Simple explanation: Imagine you have a box full of toys. If you just throw them all in, it is hard to find a specific toy. But if you label the box โ€œLEGOโ€ and put all the LEGO pieces inside, it is easy to find. Structured data is like labelling your content so search engines can find it easily.

Real-life example: A library has a catalogue that tells you where each book is. That catalogue is like structured data.

School example: Your school has a timetable that tells you which subject is on which day โ€“ that is structured data.

Home example: Your mum has a recipe book with sections โ€“ โ€œSoupsโ€, โ€œRice Dishesโ€, โ€œSnacksโ€ โ€“ that is structured data.

Nigerian example: In a Nigerian market, shops are grouped by what they sell โ€“ โ€œFoodstuffsโ€, โ€œClothingโ€, โ€œElectronicsโ€ โ€“ that is structured data.

Illustration:

        Without structured data:
        +----------------------------------+
        |  "This is a recipe for Jollof   |
        |  rice. It has rice, tomatoes,   |
        |  and spices. Cook for 30 mins." |
        +----------------------------------+
        Search engine: "I think this is about food... maybe?"

        With structured data:
        +----------------------------------+
        |  Recipe                           |
        |  Name: Jollof Rice               |
        |  Ingredients: Rice, Tomatoes...  |
        |  Cooking Time: 30 minutes        |
        |  Rating: โ˜…โ˜…โ˜…โ˜…โ˜†                   |
        +----------------------------------+
        Search engine: "This is a recipe! I can show it with rich results!"
    
๐Ÿ“Œ Mini summary: Structured data is labelling your content so search engines can understand it better. It helps your website appear in rich results.

Lesson 2: Why Structured Data Matters for SEO

Definition: SEO (Search Engine Optimisation) is the practice of making your website easy to find on search engines. Structured data is a powerful SEO tool.

Why important: Websites with structured data are more likely to appear in rich results โ€“ which get more clicks.

Simple explanation: Structured data is like a bright sign on your shop. It helps people notice your shop and come inside.

Real-life example: A restaurant with a big, bright sign on the road gets more customers than one with a small, hidden sign.

School example: A student who writes their name clearly on their project gets noticed more than one who does not.

Home example: A house with a visible house number is easier to find than one without.

Nigerian example: A shop in a Nigerian market with a big sign saying โ€œFresh Tomatoesโ€ gets more customers than one with no sign.

Illustration:

        Without structured data:
        Normal search result: "Jollof Rice Recipe โ€“ My Blog"
        Click-through rate: low

        With structured data:
        Rich result:
        +----------------------------------+
        |  Jollof Rice Recipe              |
        |  โญโญโญโญ (4.5)                   |
        |  โฑ 30 mins | ๐Ÿš Rice, Tomatoes |
        |  [Picture of Jollof Rice]        |
        +----------------------------------+
        Click-through rate: high!
    
๐Ÿ“Œ Mini summary: Structured data improves your SEO by making your website appear in rich results, which attract more clicks.

Lesson 3: Introduction to Schema.org

Definition: Schema.org is a vocabulary (a set of terms) for structured data. It was created by Google, Microsoft, Yahoo, and Yandex to help web developers add structured data to their pages.

Why important: Schema.org is the standard for structured data. If you use it, search engines will understand your content easily.

Simple explanation: Schema.org is like a dictionary of labels. It tells you what labels to use for different types of content โ€“ like โ€œRecipeโ€, โ€œPersonโ€, โ€œProductโ€, and โ€œEventโ€.

Real-life example: A library has a standard way to label books โ€“ by author, title, and genre. Schema.org is like that standard for websites.

School example: Your school has a standard way to label subjects โ€“ โ€œMathsโ€, โ€œEnglishโ€, โ€œScienceโ€. Schema.org is like that for content.

Home example: Your family has a standard way to label storage boxes โ€“ โ€œChristmas Decorationsโ€, โ€œWinter Clothesโ€. Schema.org is like that for web content.

Nigerian example: In Nigeria, there is a standard way to label roads โ€“ โ€œLagos-Ibadan Expresswayโ€. Schema.org is like that for web content.

Key Schema.org types:

  • Thing โ€“ the most general type.
  • Person โ€“ a person.
  • Organization โ€“ a company or group.
  • Product โ€“ an item for sale.
  • Recipe โ€“ cooking instructions.
  • Event โ€“ a concert, conference, or party.
  • Review โ€“ a rating or review.
  • Article โ€“ a news or blog article.
๐Ÿ“Œ Mini summary: Schema.org is a standard vocabulary for structured data. It tells you what labels to use for different types of content.

Lesson 4: Microdata โ€“ The HTML Way to Add Structured Data

Definition: Microdata is a way to add structured data to your HTML using special attributes โ€“ itemscope, itemtype, and itemprop.

Why important: Microdata is one of the easiest ways to add structured data to your HTML. It works with Schema.org vocabulary.

Simple explanation: Microdata is like sticky notes that you attach to your HTML to tell search engines what each part means.

Real-life example: In a museum, each painting has a small card next to it with the title and artist โ€“ that is like microdata.

School example: In your notebook, you write a title at the top of each page โ€“ that is like microdata.

Home example: You put labels on jars in the kitchen โ€“ โ€œSugarโ€, โ€œRiceโ€, โ€œBeansโ€ โ€“ that is like microdata.

Nigerian example: In a Nigerian market, a seller puts a sign on their stall โ€“ โ€œFresh Tomatoesโ€ โ€“ that is like microdata.

Microdata attributes:

  • itemscope โ€“ creates a new item (a thing).
  • itemtype โ€“ specifies the type of the item (from Schema.org).
  • itemprop โ€“ specifies a property of the item.
๐Ÿ“Œ Mini summary: Microdata uses special HTML attributes (itemscope, itemtype, itemprop) to add structured data to your pages.

Lesson 5: The itemscope Attribute โ€“ Creating an Item

Definition: itemscope creates a new item. It tells the browser, โ€œThis part of the page is about one thing.โ€

Why important: It defines the scope of an item โ€“ everything inside is part of that item.

Simple explanation: itemscope is like a box. You put your content inside the box and label it.

Code example:

        <div itemscope>
            <!-- everything inside is part of this item -->
        </div>
    
๐Ÿ“Œ Mini summary: itemscope creates a new item. All content inside is part of that item.

Lesson 6: The itemtype Attribute โ€“ Specifying the Type

Definition: itemtype specifies the type of the item using a Schema.org URL.

Why important: It tells search engines exactly what kind of thing this is โ€“ a person, a recipe, a product, etc.

Simple explanation: itemtype is like the label on the box. It tells you what is inside.

Code example:

        <div itemscope itemtype="https://schema.org/Recipe">
            <!-- this is a recipe -->
        </div>
    
๐Ÿ“Œ Mini summary: itemtype tells search engines what type of thing this is. Use a Schema.org URL.

Lesson 7: The itemprop Attribute โ€“ Adding Properties

Definition: itemprop specifies a property of the item โ€“ like a name, a description, an image, or a rating.

Why important: It gives search engines details about the item โ€“ like โ€œThis recipe is called Jollof Riceโ€.

Simple explanation: itemprop is like details on the label โ€“ โ€œIngredientsโ€, โ€œCooking Timeโ€, โ€œRatingโ€.

Code example:

        <div itemscope itemtype="https://schema.org/Recipe">
            <h1 itemprop="name">Jollof Rice</h1>
            <p itemprop="description">A delicious Nigerian rice dish.</p>
            <p itemprop="cookTime">PT30M</p>
        </div>
    
๐Ÿ“Œ Mini summary: itemprop adds details (properties) to your item. It tells search engines specific information about the item.

Lesson 8: Marking Up a Person

Definition: You can mark up a person using the Person type from Schema.org.

Why important: It helps search engines understand information about people โ€“ like authors, artists, or team members.

Code example:

        <div itemscope itemtype="https://schema.org/Person">
            <h1 itemprop="name">Chidi Okafor</h1>
            <p itemprop="jobTitle">Chef and Food Blogger</p>
            <p itemprop="address">Lagos, Nigeria</p>
        </div>
    
๐Ÿ“Œ Mini summary: Use Person to mark up information about a person โ€“ like their name, job, and location.

Lesson 9: Marking Up an Organisation

Definition: You can mark up an organisation using the Organization type from Schema.org.

Why important: It helps search engines understand information about companies, schools, and non-profits.

Code example:

        <div itemscope itemtype="https://schema.org/Organization">
            <h1 itemprop="name">Unity Academy</h1>
            <p itemprop="description">A school in Lagos, Nigeria.</p>
            <p itemprop="address">Lagos, Nigeria</p>
        </div>
    
๐Ÿ“Œ Mini summary: Use Organization to mark up information about a company, school, or group.

Lesson 10: Marking Up a Product

Definition: You can mark up a product using the Product type from Schema.org.

Why important: It helps search engines display product information โ€“ like price, availability, and reviews โ€“ in rich results.

Code example:

        <div itemscope itemtype="https://schema.org/Product">
            <h1 itemprop="name">Nigerian Jollof Rice Mix</h1>
            <p itemprop="description">A traditional Nigerian seasoning mix.</p>
            <p itemprop="price">โ‚ฆ2,500</p>
        </div>
    
๐Ÿ“Œ Mini summary: Use Product to mark up information about items for sale โ€“ like name, description, and price.

Lesson 11: Marking Up a Recipe

Definition: You can mark up a recipe using the Recipe type from Schema.org.

Why important: It helps search engines display recipe information โ€“ like ingredients, cooking time, and ratings โ€“ in rich results.

Code example:

        <div itemscope itemtype="https://schema.org/Recipe">
            <h1 itemprop="name">Jollof Rice</h1>
            <p itemprop="description">A classic Nigerian rice dish.</p>
            <p itemprop="cookTime">PT30M</p>
            <ul>
                <li itemprop="recipeIngredient">Rice</li>
                <li itemprop="recipeIngredient">Tomatoes</li>
                <li itemprop="recipeIngredient">Onions</li>
            </ul>
            <div itemprop="aggregateRating" itemscope itemtype="https://schema.org/AggregateRating">
                <p>Rating: <span itemprop="ratingValue">4.5</span> / 5</p>
            </div>
        </div>
    
๐Ÿ“Œ Mini summary: Use Recipe to mark up recipes โ€“ with ingredients, cooking time, and ratings.

Lesson 12: Marking Up an Event

Definition: You can mark up an event using the Event type from Schema.org.

Why important: It helps search engines display event information โ€“ like date, location, and tickets โ€“ in rich results.

Code example:

        <div itemscope itemtype="https://schema.org/Event">
            <h1 itemprop="name">Lagos Food Festival</h1>
            <p itemprop="startDate">2025-12-25T10:00</p>
            <p itemprop="location">Lagos, Nigeria</p>
        </div>
    
๐Ÿ“Œ Mini summary: Use Event to mark up events โ€“ like concerts, conferences, and festivals.

Lesson 13: Marking Up a Review

Definition: You can mark up a review using the Review type from Schema.org.

Why important: It helps search engines display review information โ€“ like ratings and comments โ€“ in rich results.

Code example:

        <div itemscope itemtype="https://schema.org/Review">
            <h1 itemprop="name">Great Jollof Rice!</h1>
            <div itemprop="reviewRating" itemscope itemtype="https://schema.org/Rating">
                <p>Rating: <span itemprop="ratingValue">5</span> / 5</p>
            </div>
            <p itemprop="reviewBody">This is the best Jollof rice I have ever tasted!</p>
            <p itemprop="author">By Chidi</p>
        </div>
    
๐Ÿ“Œ Mini summary: Use Review to mark up reviews โ€“ with ratings and comments.

Lesson 14: Testing Your Structured Data

Definition: You can test your structured data using Google's Rich Results Test tool.

Why important: It checks if your structured data is correct and shows you how it will appear in search results.

How to use it:

  • Go to search.google.com/test/rich-results.
  • Enter your URL or paste your HTML code.
  • Click โ€œTest URLโ€ or โ€œTest Codeโ€.
  • See the results and fix any errors.
๐Ÿ“Œ Mini summary: Use Google's Rich Results Test to check if your structured data is correct and see how it will appear.

๐Ÿ“– Key Vocabulary

  • Structured Data: Organised information that helps search engines understand your content.
  • Schema.org: A standard vocabulary for structured data.
  • Microdata: A way to add structured data to HTML using special attributes.
  • itemscope: Creates a new item.
  • itemtype: Specifies the type of an item (from Schema.org).
  • itemprop: Specifies a property of an item.
  • Rich Results: Enhanced search results with pictures, ratings, and other information.
  • SEO: Search Engine Optimisation โ€“ making your website easy to find.
  • Person: A Schema.org type for a person.
  • Organization: A Schema.org type for a company or group.
  • Product: A Schema.org type for an item for sale.
  • Recipe: A Schema.org type for cooking instructions.
  • Event: A Schema.org type for a concert, conference, etc.
  • Review: A Schema.org type for a rating or review.

๐Ÿง  Important Concepts

  • Structured data is invisible to users but visible to search engines. It does not change how your page looks, but it helps search engines understand it.
  • Schema.org is the standard. Always use Schema.org vocabulary for structured data.
  • Microdata is one of several formats. Other formats include RDFa and JSON-LD (which we will cover later).
  • Rich results are better for users. They attract more clicks and improve user experience.
  • Testing is important. Always test your structured data to make sure it works.

๐Ÿชœ Step-by-step Explanations

How to add structured data to a recipe:

  1. Find the Schema.org type for a recipe: https://schema.org/Recipe.
  2. Add itemscope and itemtype to the container.
  3. Add itemprop for the name, description, and cooking time.
  4. Add itemprop="recipeIngredient" for each ingredient.
  5. Add an aggregate rating using AggregateRating.
  6. Test with Google's Rich Results Test.

How to test structured data:

  1. Go to search.google.com/test/rich-results.
  2. Paste your URL or HTML code.
  3. Click โ€œTest URLโ€ or โ€œTest Codeโ€.
  4. Review the results and fix any errors.

๐ŸŒ Real-life Examples

  • Example 1: A restaurant website uses structured data to show its menu items, prices, and opening hours in search results.
  • Example 2: An e-commerce site uses structured data to show product prices, availability, and reviews in rich results.
  • Example 3: A blog uses structured data to show article headlines, authors, and publish dates in search results.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Example 1: A Nigerian food blog uses Recipe to mark up Egusi soup, Suya, and Jollof rice recipes.
  • Example 2: A Nigerian e-commerce site uses Product to mark up items like phone cases, clothes, and shoes.
  • Example 3: A Nigerian event website uses Event to mark up concerts, festivals, and cultural events.

๐ŸŽฎ Fun Examples Children Can Relate To

  • Example 1: A video game website uses Product to mark up game titles, prices, and ratings.
  • Example 2: A school project uses Article to mark up a news article about a school event.
  • Example 3: A movie fan site uses Movie to mark up movie titles, directors, and release dates.

๐Ÿ  Everyday Examples

  • Example 1: A recipe box at home โ€“ you can use Recipe to mark up family recipes.
  • Example 2: A family photo album โ€“ you can use ImageObject to mark up photos.
  • Example 3: A family events calendar โ€“ you can use Event to mark up birthdays and holidays.

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง Parent Tips

  • Tip 1: Encourage your child to add structured data to their projects โ€“ it is a professional skill.
  • Tip 2: Help them understand that structured data is like labelling โ€“ it helps search engines find things.
  • Tip 3: Remind them to always test their structured data โ€“ it is easy to make mistakes.

๐Ÿ’ก Interesting Facts

  • Fact 1: Schema.org was created in 2011 by Google, Microsoft, Yahoo, and Yandex.
  • Fact 2: Over 30% of websites use some form of structured data.
  • Fact 3: Rich results can increase click-through rates by up to 30%.

๐Ÿค” Did You Know?

  • Did you know? That you can use structured data to mark up almost anything โ€“ people, places, events, products, and more?
  • Did you know? That Google uses structured data to power features like Knowledge Panels and Carousels?
  • Did you know? That structured data can also be used for voice search โ€“ like when you ask Siri or Google Assistant?

๐Ÿง  Remember This

  • 1. Structured data helps search engines understand your content.
  • 2. Use Schema.org vocabulary.
  • 3. Use microdata attributes โ€“ itemscope, itemtype, itemprop.
  • 4. Always test your structured data with Google's Rich Results Test.
  • 5. Structured data is invisible to users but valuable for SEO.

โŒ Common Mistakes

  • Mistake 1: Forgetting to close the itemscope or itemtype attributes.
  • Mistake 2: Using the wrong itemtype URL โ€“ always use https://schema.org/....
  • Mistake 3: Not using itemprop on the right elements โ€“ it must be on the element that contains the property value.
  • Mistake 4: Not testing structured data โ€“ it is easy to make mistakes.
  • Mistake 5: Using structured data on content that is not visible to users โ€“ only mark up visible content.

โœ… Best Practices

  • Practice 1: Always use Schema.org vocabulary.
  • Practice 2: Only mark up content that is visible to users.
  • Practice 3: Use the most specific type possible โ€“ e.g., Recipe instead of Thing.
  • Practice 4: Test your structured data with Google's Rich Results Test.
  • Practice 5: Keep your structured data up to date โ€“ if your content changes, update the structured data.

๐Ÿ“Š ASCII Illustrations

Microdata Structure

        +------------------------------------------+
        |  <div itemscope itemtype="...">          |
        |    <h1 itemprop="name">...</h1>         |
        |    <p itemprop="description">...</p>   |
        |    <span itemprop="price">...</span>   |
        |  </div>                                  |
        +------------------------------------------+
        itemscope = "this is a thing"
        itemtype = "this is what kind of thing"
        itemprop = "this is a detail about the thing"
    

Structured Data Flow

        You add structured data to your HTML
                    |
                    V
        Search engine crawls your page
                    |
                    V
        Search engine reads the structured data
                    |
                    V
        Search engine shows rich results
                    |
                    V
        Users see your rich result and click! ๐ŸŽ‰
    

Rich Results Example

        Normal result:
        ----------------------------------------
        Jollof Rice Recipe | My Blog
        ----------------------------------------

        Rich result:
        ----------------------------------------
        โญโญโญโญ (4.5) Jollof Rice Recipe
        โฑ 30 mins | ๐Ÿš Rice, Tomatoes, Onions
        [Picture of Jollof Rice]
        ----------------------------------------
    

๐Ÿ“‹ Comparison Tables

Structured Data Formats

Format Description Best used for
Microdata Uses HTML attributes (itemscope, itemtype, itemprop). Simple structured data directly in HTML.
RDFa Uses HTML attributes (vocab, typeof, property). More complex structured data.
JSON-LD Uses a <script> tag with JSON data. Most recommended format โ€“ easy to use and maintain.

Schema.org Types

Type Used for Example properties
Person A person name, jobTitle, address
Organization A company or group name, description, address
Product An item for sale name, description, price
Recipe Cooking instructions name, cookTime, recipeIngredient
Event An event name, startDate, location
Review A rating or review reviewRating, reviewBody, author

๐Ÿ“š End-of-Module Summary

Amazing work, structured data master! ๐Ÿ” You have completed Module 1 of HTML Level Three.

Let us recap what you have learned:

  • What structured data is and why it matters for SEO.
  • How to use Schema.org โ€“ the standard vocabulary for structured data.
  • How to use microdata attributes โ€“ itemscope, itemtype, and itemprop.
  • How to mark up different types of content โ€“ People, Organisations, Products, Recipes, Events, and Reviews.
  • How to test your structured data using Google's Rich Results Test.
  • The difference between microdata, RDFa, and JSON-LD.

You now know how to help search engines understand your content and make your website stand out in search results. This is a professional skill used by developers at top companies!

โ“ Frequently Asked Questions

  • Q1: What is the difference between structured data and regular HTML?
    A: Regular HTML tells the browser how to display content. Structured data tells search engines what the content is about.
  • Q2: Do I need to add structured data to every page?
    A: You should add it to pages where it makes sense โ€“ like products, recipes, events, and articles.
  • Q3: Does structured data change how my page looks?
    A: No โ€“ structured data is invisible to users. It only helps search engines.
  • Q4: What is the best format for structured data?
    A: JSON-LD is the most recommended format because it is easy to use and maintain.
  • Q5: How do I know if my structured data is working?
    A: Use Google's Rich Results Test or Schema.org's validator.
  • Q6: Can I use structured data on an existing website?
    A: Yes โ€“ you can add structured data to any HTML page.
  • Q7: Does structured data guarantee rich results?
    A: No โ€“ search engines decide when to show rich results. But structured data increases your chances.
  • Q8: What is the difference between microdata and JSON-LD?
    A: Microdata is added directly to HTML. JSON-LD is added in a <script> tag.
  • Q9: Can I use multiple types on one page?
    A: Yes โ€“ you can mark up different types of content on the same page.
  • Q10: Is structured data only for Google?
    A: No โ€“ other search engines like Bing and Yahoo also use structured data.

๐Ÿ”— Matching Exercises

Match the microdata attribute on the left with its correct description on the right.

Attribute Description
itemscope A. Specifies the type of an item
itemtype B. Specifies a property of an item
itemprop C. Creates a new item

(Answers: 1-C, 2-A, 3-B)

๐Ÿ“ Scenario-based Exercises

Scenario 1: You are building a website for a Nigerian bakery called โ€œSweet Delightsโ€. You want to show the bakeryโ€™s name, address, and opening hours in search results.

Question: Write the HTML code using microdata to mark up the bakery as an Organization.

Scenario 2: You are building a recipe page for โ€œJollof Riceโ€. You want to show the cooking time, ingredients, and rating in search results.

Question: Write the HTML code using microdata to mark up the recipe with Recipe and AggregateRating.

๐Ÿ‘ฅ Group Activity

Activity: In groups of 3โ€“4 students, choose a real-world topic (like a Nigerian restaurant, a school, or a product). Write a page of HTML that includes structured data for that topic.

  • One student writes the HTML.
  • One student adds the microdata attributes.
  • One student tests the structured data using Google's Rich Results Test.
  • One student presents the results to the class.

๐Ÿง‘โ€๐Ÿ’ป Individual Activity

Activity: Create a page about your favourite Nigerian food. Include:

  • A Recipe type with name, description, cooking time, and ingredients.
  • An AggregateRating with a rating value.
  • Test your structured data using Google's Rich Results Test.
  • Fix any errors.

Save it as recipe.html and submit it.

๐Ÿ› ๏ธ Mini Project

Project: Structured Data Portfolio

Instructions: Create a page about yourself and your interests. Your page must include structured data for:

  • โœ… A Person โ€“ your name, job title, and location.
  • โœ… An Organization โ€“ your school or a club you belong to.
  • โœ… A Product โ€“ a product you like or use.
  • โœ… A Recipe โ€“ your favourite Nigerian recipe.
  • โœ… An Event โ€“ an event you attended or want to attend.

Test your structured data with Google's Rich Results Test and fix any errors.

Bonus: Add an Article type for a blog post you wrote.

๐Ÿ“‹ Practical Assignment

Assignment: Create a page for a Nigerian restaurant called โ€œTasty Bitesโ€. Include:

  • An Organization type with the restaurant name, address, and phone number.
  • A Product type for the โ€œJollof Riceโ€ dish with price and description.
  • An AggregateRating with a rating value.
  • A Menu type (you can research this on Schema.org).
  • Test your structured data with Google's Rich Results Test.
  • Submit your HTML file.

๐Ÿ”‘ Key Takeaways

  • 1. Structured data helps search engines understand your content.
  • 2. Use Schema.org vocabulary for structured data.
  • 3. Microdata uses itemscope, itemtype, and itemprop.
  • 4. Rich results attract more clicks and improve user experience.
  • 5. Always test your structured data with Google's Rich Results Test.
  • 6. Structured data is a professional skill used by top developers.

๐Ÿ’ฌ Classroom Discussion Questions

  • 1. Why do you think structured data is important for SEO?
  • 2. How would you explain microdata to someone who has never coded before?
  • 3. What are some ways you can use structured data on your own projects?
  • 4. Why is it important to test structured data?
  • 5. How can structured data help small businesses in Nigeria?

๐Ÿš€ Preparation for Module 2

Excellent work on Module 1! You have learned how to add structured data to your HTML pages. In Module 2, we will dive into Advanced HTML5 APIs โ€“ Canvas. You will learn how to:

  • Use the <canvas> element to draw graphics.
  • Draw shapes, lines, and circles.
  • Add colours, gradients, and text.
  • Create simple animations.
  • Build a drawing app.

Before you start Module 2, make sure you can:

  • Add structured data to a page using microdata.
  • Test your structured data with Google's Rich Results Test.
  • Understand the difference between itemscope, itemtype, and itemprop.

Keep learning and building โ€“ you are on your way to becoming a professional web developer! ๐Ÿ’ป๐ŸŒŸ


Module 1: Structured Data & Microdata • Written with ๐Ÿ’– for young coders in Nigeria and around the world.

3

Module Two

Module 2: Advanced HTML5 APIs โ€“ Canvas

๐ŸŽจ Module 2: Advanced HTML5 APIs โ€“ Canvas

Drawing graphics, shapes, and animations right in your browser!

๐Ÿ“– Module Introduction

Welcome to Module 2 of your HTML Level Three journey! In Module 1, you learned how to add structured data to your pages, helping search engines understand your content better.

Now, in Module 2, we are going to learn about one of the most exciting and creative features of HTML5 โ€“ the Canvas API!

The Canvas element is like a digital sketchpad inside your web page. You can use it to draw shapes, lines, text, and images โ€“ and even create animations and games!

In this module, you will learn:

  • What the <canvas> element is and how to use it.
  • How to draw rectangles, circles, and lines.
  • How to add colours, gradients, and styles.
  • How to draw text and images on the canvas.
  • How to create simple animations.
  • How to build a drawing app.

Think of this module as learning to paint on the web. By the end, you will be able to create interactive graphics that amaze your friends and family. Let us begin!

๐ŸŽฏ Learning Objectives

By the end of this module, you will be able to:

  • Explain what the Canvas API is and why it is useful.
  • Use the <canvas> element in HTML.
  • Draw rectangles, circles, and lines on the canvas.
  • Apply colours, gradients, and stroke styles.
  • Draw text and images on the canvas.
  • Create simple animations using JavaScript.
  • Build a simple drawing app.

๐Ÿ“š Warm-up Story: Aishaโ€™s Art Gallery

Aisha was a 13-year-old girl who loved art. She could draw beautiful pictures of people, animals, and landscapes. She wanted to share her art with the world, so she decided to create an online art gallery.

Aishaโ€™s big sister, who was a web developer, said, โ€œAisha, you can use HTML Canvas to let people draw on your website! They can create their own art right in the browser.โ€

Aisha was excited. She learned how to use the <canvas> element and JavaScript to draw shapes, lines, and colours. She built a simple drawing app where visitors could click and drag to draw. Her art gallery became a hit โ€“ people loved creating their own digital art!

In this module, you will learn exactly what Aisha learned. You will learn how to use the Canvas API to draw, create, and animate right in your web pages. Let us get started!

๐Ÿงฉ Main Lessons

Lesson 1: What is the Canvas API?

Definition: The Canvas API is a way to draw graphics on a web page using the <canvas> element and JavaScript.

Why important: It lets you create interactive graphics, animations, and even games โ€“ all inside a web page.

Simple explanation: Think of the Canvas element as a blank piece of paper on your web page. JavaScript is like a paintbrush that you can use to draw on that paper.

Real-life example: A digital whiteboard โ€“ you can draw on it with a stylus or your finger.

School example: A digital blackboard โ€“ your teacher can write and draw on it using a computer.

Home example: A drawing app on your tablet โ€“ you can draw pictures with your fingers.

Nigerian example: A digital art studio โ€“ you can create beautiful digital paintings just like traditional artists.

Illustration:

        HTML page:
        +----------------------------------+
        |  <canvas>                       |
        |  +----------------------------+ |
        |  |  (blank canvas)            | |
        |  |                            | |
        |  |                            | |
        |  +----------------------------+ |
        |  </canvas>                     |
        +----------------------------------+
        JavaScript draws on the canvas
    
๐Ÿ“Œ Mini summary: The Canvas API lets you draw graphics on a web page. The <canvas> element is the paper, and JavaScript is the paintbrush.

Lesson 2: The <canvas> Element

Definition: <canvas> is an HTML element that provides a drawing surface for graphics.

Why important: It is the container where all your drawings will appear.

Simple explanation: <canvas> is like a canvas that an artist uses โ€“ it holds the artwork.

Code example:

        <canvas id="myCanvas" width="400" height="300">
            Your browser does not support the canvas element.
        </canvas>
    
๐Ÿ“Œ Mini summary: <canvas> is the container for your drawings. Give it an id so you can access it with JavaScript.

Lesson 3: Getting the Canvas Context

Definition: The context is an object that provides methods (functions) for drawing on the canvas.

Why important: You need the context to actually draw anything. It is like getting the paintbrush.

Simple explanation: The context is like the toolbox that contains all the drawing tools โ€“ pens, brushes, colours, and shapes.

Code example:

        <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');
            // now you can draw using ctx!
        </script>
    
๐Ÿ“Œ Mini summary: The getContext('2d') method gives you the drawing context. You need it to draw on the canvas.

Lesson 4: Drawing Rectangles โ€“ fillRect() and strokeRect()

Definition: fillRect() draws a filled rectangle. strokeRect() draws only the outline.

Why important: Rectangles are the simplest shapes to draw โ€“ they are a great starting point.

Simple explanation: fillRect() is like painting a box with colour. strokeRect() is like drawing the outline of a box.

Code example:

        <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');

            ctx.fillStyle = 'blue';
            ctx.fillRect(50, 50, 100, 80);

            ctx.strokeStyle = 'red';
            ctx.lineWidth = 3;
            ctx.strokeRect(200, 50, 100, 80);
        </script>
    
๐Ÿ“Œ Mini summary: fillRect() draws a filled rectangle. strokeRect() draws only the outline.

Lesson 5: Drawing Circles and Arcs โ€“ arc()

Definition: arc() draws a circle or part of a circle (an arc).

Why important: Circles are used in many graphics โ€“ from buttons to smiley faces.

Simple explanation: arc() is like drawing a circle with a compass. You set the centre point, the radius, and the start/end angles.

Code example:

        <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');

            ctx.beginPath();
            ctx.arc(150, 150, 50, 0, 2 * Math.PI);
            ctx.fillStyle = 'green';
            ctx.fill();
            ctx.strokeStyle = 'darkgreen';
            ctx.stroke();
        </script>
    
๐Ÿ“Œ Mini summary: arc() draws circles and arcs. Use beginPath() and stroke() or fill() to complete the drawing.

Lesson 6: Drawing Lines โ€“ moveTo() and lineTo()

Definition: moveTo() moves the "pen" to a point. lineTo() draws a line from the current point to another point.

Why important: Lines are the building blocks for many shapes โ€“ triangles, polygons, and freehand drawings.

Simple explanation: moveTo() is like lifting your pen and placing it somewhere new. lineTo() is like drawing a line to another point.

Code example:

        <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');

            ctx.beginPath();
            ctx.moveTo(20, 20);
            ctx.lineTo(200, 20);
            ctx.lineTo(200, 200);
            ctx.lineTo(20, 200);
            ctx.closePath();
            ctx.strokeStyle = 'purple';
            ctx.lineWidth = 3;
            ctx.stroke();
        </script>
    
๐Ÿ“Œ Mini summary: moveTo() and lineTo() let you draw lines. Use closePath() to close a shape.

Lesson 7: Colours and Styles

Definition: You can set colours using fillStyle and strokeStyle.

Why important: Colours make your drawings beautiful and vibrant.

Simple explanation: fillStyle is the colour inside a shape. strokeStyle is the colour of the outline.

Code example:

        ctx.fillStyle = 'red';
        ctx.strokeStyle = 'darkred';
        ctx.lineWidth = 5;
    
๐Ÿ“Œ Mini summary: fillStyle sets the fill colour. strokeStyle sets the outline colour. lineWidth sets the outline thickness.

Lesson 8: Gradients

Definition: A gradient is a smooth transition between two or more colours.

Why important: Gradients make your graphics look professional and smooth.

Simple explanation: A gradient is like a rainbow โ€“ colours blend into each other smoothly.

Code example:

        const gradient = ctx.createLinearGradient(0, 0, 200, 200);
        gradient.addColorStop(0, 'red');
        gradient.addColorStop(1, 'blue');
        ctx.fillStyle = gradient;
        ctx.fillRect(50, 50, 200, 100);
    
๐Ÿ“Œ Mini summary: Gradients create smooth colour transitions. Use createLinearGradient() or createRadialGradient().

Lesson 9: Drawing Text โ€“ fillText() and strokeText()

Definition: fillText() draws filled text. strokeText() draws outlined text.

Why important: You can add labels, titles, and information to your canvas drawings.

Simple explanation: fillText() is like writing with a marker. strokeText() is like writing with a pen outline.

Code example:

        ctx.font = '30px Arial';
        ctx.fillStyle = 'black';
        ctx.fillText('Hello Canvas!', 50, 100);

        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 1;
        ctx.strokeText('Hello Canvas!', 50, 150);
    
๐Ÿ“Œ Mini summary: fillText() draws filled text. strokeText() draws outlined text. Use font to set the text style.

Lesson 10: Drawing Images โ€“ drawImage()

Definition: drawImage() draws an image on the canvas.

Why important: You can add photos, logos, and other images to your canvas drawings.

Simple explanation: drawImage() is like pasting a picture onto your canvas.

Code example:

        const img = new Image();
        img.src = 'logo.png';
        img.onload = function() {
            ctx.drawImage(img, 50, 50, 100, 100);
        };
    
๐Ÿ“Œ Mini summary: drawImage() adds images to your canvas. Make sure the image loads before drawing.

Lesson 11: Clearing the Canvas โ€“ clearRect()

Definition: clearRect() erases a rectangular area of the canvas.

Why important: You need it to clear the canvas before drawing new frames in an animation.

Simple explanation: clearRect() is like erasing part of your drawing.

Code example:

        ctx.clearRect(0, 0, canvas.width, canvas.height);
    
๐Ÿ“Œ Mini summary: clearRect() erases the canvas. Use it to prepare for new drawings or animations.

Lesson 12: Simple Animations

Definition: Animations are created by repeatedly clearing and redrawing the canvas with small changes.

Why important: Animations make your web pages dynamic and engaging.

Simple explanation: Animation is like a flipbook โ€“ each page is slightly different, and when you flip through them quickly, it looks like motion.

Code example:

        let x = 0;
        function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = 'red';
            ctx.fillRect(x, 50, 50, 50);
            x += 1;
            requestAnimationFrame(draw);
        }
        draw();
    
๐Ÿ“Œ Mini summary: Animations are created by repeatedly clearing and redrawing the canvas. Use requestAnimationFrame() for smooth animation.

๐Ÿ“– Key Vocabulary

  • Canvas: An HTML element for drawing graphics.
  • Context: An object that provides drawing methods.
  • fillRect: Draws a filled rectangle.
  • strokeRect: Draws an outlined rectangle.
  • arc: Draws a circle or arc.
  • moveTo: Moves the pen to a point.
  • lineTo: Draws a line to a point.
  • fillStyle: Sets the fill colour.
  • strokeStyle: Sets the outline colour.
  • Gradient: A smooth colour transition.
  • fillText: Draws filled text.
  • strokeText: Draws outlined text.
  • drawImage: Draws an image on the canvas.
  • clearRect: Erases part of the canvas.
  • Animation: Moving graphics created by repeated drawing.

๐Ÿง  Important Concepts

  • Canvas is pixel-based. Everything you draw is on a grid of pixels.
  • Draw order matters. Things drawn later appear on top of earlier drawings.
  • Animation requires clearing. Always clear the canvas before drawing the next frame.
  • Use requestAnimationFrame() for smooth animations. It is better than setInterval().

๐Ÿชœ Step-by-step Explanations

How to draw a circle on the canvas:

  1. Get the canvas element and context.
  2. Call beginPath() to start a new path.
  3. Call arc(x, y, radius, startAngle, endAngle).
  4. Set fillStyle and strokeStyle.
  5. Call fill() and stroke().

How to create a simple animation:

  1. Create a draw() function.
  2. Clear the canvas with clearRect().
  3. Draw your shapes with updated positions.
  4. Call requestAnimationFrame(draw) to repeat.

๐ŸŒ Real-life Examples

  • Example 1: Google Maps uses Canvas to draw maps and routes.
  • Example 2: Online drawing apps like Sketchpad use Canvas.
  • Example 3: Games like โ€œChrome Dino Gameโ€ use Canvas for graphics.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Example 1: A Nigerian art website could use Canvas to let users draw traditional patterns.
  • Example 2: A Nigerian educational site could use Canvas to create interactive charts.
  • Example 3: A Nigerian game developer could use Canvas to build mobile games.

๐ŸŽฎ Fun Examples Children Can Relate To

  • Example 1: A drawing app where you can draw with your mouse.
  • Example 2: A bouncing ball animation.
  • Example 3: A simple game where you click on moving targets.

๐Ÿ  Everyday Examples

  • Example 1: A whiteboard app for family planning.
  • Example 2: A digital sketchpad for drawing.
  • Example 3: A photo editor that lets you add shapes and text.

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง Parent Tips

  • Tip 1: Encourage your child to experiment with different shapes and colours.
  • Tip 2: Help them understand that Canvas is a powerful tool for creativity.
  • Tip 3: Remind them that animations are just many drawings played quickly.

๐Ÿ’ก Interesting Facts

  • Fact 1: The Canvas API was introduced in HTML5 in 2004.
  • Fact 2: Canvas is used by millions of websites for games and visualisations.
  • Fact 3: Canvas can even be used for video processing and effects.

๐Ÿค” Did You Know?

  • Did you know? That Canvas can be used to create 3D graphics using WebGL?
  • Did you know? That the Chrome Dino Game is built using Canvas?
  • Did you know? That Canvas is faster than SVG for animations?

๐Ÿง  Remember This

  • 1. Canvas is for drawing graphics on a web page.
  • 2. You need the getContext('2d') to draw.
  • 3. Use fillRect() for filled shapes and strokeRect() for outlines.
  • 4. Use arc() for circles and moveTo()/lineTo() for lines.
  • 5. Use requestAnimationFrame() for smooth animations.

โŒ Common Mistakes

  • Mistake 1: Forgetting to set the canvas width and height โ€“ the canvas will be tiny.
  • Mistake 2: Not calling beginPath() before drawing a new shape.
  • Mistake 3: Not using closePath() to close paths.
  • Mistake 4: Forgetting to clear the canvas before an animation โ€“ it will look messy.
  • Mistake 5: Using setInterval() instead of requestAnimationFrame() โ€“ it is less smooth.

โœ… Best Practices

  • Practice 1: Always set the canvas width and height.
  • Practice 2: Use beginPath() before drawing each shape.
  • Practice 3: Use requestAnimationFrame() for animations.
  • Practice 4: Save and restore the canvas state using save() and restore().
  • Practice 5: Keep your code organised and well-commented.

๐Ÿ“Š ASCII Illustrations

Canvas Drawing Flow

        HTML page loads
              |
              V
        Canvas element is created
              |
              V
        JavaScript gets the canvas context
              |
              V
        You draw shapes, lines, text
              |
              V
        The drawing appears on the canvas!
    

Animation Loop

        Start animation
              |
              V
        Clear the canvas
              |
              V
        Update positions of objects
              |
              V
        Draw objects on the canvas
              |
              V
        Wait for next frame (requestAnimationFrame)
              |
              V
        Repeat! ๐Ÿ”
    

Canvas Coordinates

        (0,0) ---------- (400,0)
          |                 |
          |   Canvas        |
          |                 |
        (0,300) -------- (400,300)
    

๐Ÿ“‹ Comparison Tables

Drawing Methods

Method What it does Example
fillRect() Draws a filled rectangle fillRect(10, 10, 100, 50)
strokeRect() Draws an outlined rectangle strokeRect(10, 10, 100, 50)
arc() Draws a circle or arc arc(100, 100, 50, 0, 2*Math.PI)
moveTo() Moves the pen moveTo(10, 10)
lineTo() Draws a line lineTo(200, 200)
fillText() Draws filled text fillText('Hello', 10, 50)
drawImage() Draws an image drawImage(img, 10, 10)
clearRect() Erases a rectangle clearRect(0, 0, 400, 300)

Colour Properties

Property What it does Example
fillStyle Sets the fill colour fillStyle = 'red'
strokeStyle Sets the outline colour strokeStyle = 'blue'
lineWidth Sets the outline thickness lineWidth = 3
font Sets the text style font = '30px Arial'

๐Ÿ“š End-of-Module Summary

Brilliant work, canvas artist! ๐ŸŽจ You have completed Module 2 of HTML Level Three.

Let us recap what you have learned:

  • What the Canvas API is and how to use the <canvas> element.
  • How to get the drawing context with getContext('2d').
  • How to draw rectangles with fillRect() and strokeRect().
  • How to draw circles with arc().
  • How to draw lines with moveTo() and lineTo().
  • How to add colours, gradients, and styles.
  • How to draw text and images on the canvas.
  • How to create animations using requestAnimationFrame().

You now know how to draw, create, and animate right in your web pages. This is a powerful skill used by game developers, data visualisers, and creative coders around the world!

โ“ Frequently Asked Questions

  • Q1: What is the difference between Canvas and SVG?
    A: Canvas is pixel-based (like a photo). SVG is vector-based (like a drawing). Canvas is better for animations, SVG is better for scalable graphics.
  • Q2: Do I need a special library to use Canvas?
    A: No โ€“ Canvas is built into HTML5. You just need HTML, CSS, and JavaScript.
  • Q3: Can I draw 3D graphics with Canvas?
    A: Yes โ€“ you can use WebGL (3D context) for 3D graphics.
  • Q4: How do I clear the canvas?
    A: Use clearRect(0, 0, canvas.width, canvas.height).
  • Q5: Can I save what I draw on the canvas?
    A: Yes โ€“ use canvas.toDataURL() to get an image.
  • Q6: What is requestAnimationFrame()?
    A: It is a method that tells the browser to run a function before the next repaint, creating smooth animations.
  • Q7: Can I draw on Canvas with the mouse?
    A: Yes โ€“ you can use mouse events like mousemove and mousedown.
  • Q8: Is Canvas accessible?
    A: Canvas content is not accessible to screen readers. You should provide alternative text or use ARIA.
  • Q9: Can I use Canvas on mobile devices?
    A: Yes โ€“ Canvas works on mobile browsers. You can use touch events.
  • Q10: What are some popular Canvas libraries?
    A: Libraries like Fabric.js, Paper.js, and Three.js make Canvas easier to use.

๐Ÿ”— Matching Exercises

Match the Canvas method on the left with its correct description on the right.

Method Description
fillRect() A. Draws a filled rectangle
arc() B. Draws a circle or arc
moveTo() C. Moves the pen to a point
lineTo() D. Draws a line to a point
fillText() E. Draws filled text
drawImage() F. Draws an image
clearRect() G. Erases a rectangle

(Answers: 1-A, 2-B, 3-C, 4-D, 5-E, 6-F, 7-G)

๐Ÿ“ Scenario-based Exercises

Scenario 1: You want to create a simple drawing app where users can draw with their mouse on a canvas.

Question: Write the HTML and JavaScript code for a canvas that responds to mouse events to draw lines.

Scenario 2: You want to create an animation of a bouncing ball. The ball moves across the screen and bounces off the edges.

Question: Write the JavaScript code for a bouncing ball animation using requestAnimationFrame().

๐Ÿ‘ฅ Group Activity

Activity: In groups of 3โ€“4 students, build a simple drawing app together. One student handles the HTML, one writes the JavaScript for drawing, one adds colours, and one adds a clear button.

  • Use <canvas> with a fixed size.
  • Add mouse events to draw lines.
  • Add a colour picker (using an HTML input type="color").
  • Add a clear button that erases the canvas.

Present your drawing app to the class.

๐Ÿง‘โ€๐Ÿ’ป Individual Activity

Activity: Create a page with a canvas that draws a smiley face. Your smiley face should include:

  • A circle for the face.
  • Two circles for eyes.
  • A curve for the mouth.
  • Colours for the face and eyes.

Save it as smiley.html and open it in your browser.

๐Ÿ› ๏ธ Mini Project

Project: Interactive Drawing App

Instructions: Build a complete drawing app with the following features:

  • โœ… A canvas where users can draw with their mouse.
  • โœ… A colour picker to change the drawing colour.
  • โœ… A range slider to change the brush size.
  • โœ… A clear button to erase the canvas.
  • โœ… An undo button to remove the last stroke.

Bonus: Add a save button that lets users download their drawing as an image.

๐Ÿ“‹ Practical Assignment

Assignment: Create a page with a canvas that draws a house. Your house should include:

  • A rectangle for the house body.
  • A triangle for the roof.
  • A rectangle for the door.
  • Two squares for windows.
  • A path or grass using lines.

Use colours to make it look nice. Submit your HTML file.

๐Ÿ”‘ Key Takeaways

  • 1. Canvas is a powerful API for drawing graphics on the web.
  • 2. You need the getContext('2d') to start drawing.
  • 3. Use fillRect(), arc(), and lineTo() for shapes.
  • 4. Use fillStyle, strokeStyle, and lineWidth for styles.
  • 5. Use requestAnimationFrame() for smooth animations.
  • 6. Canvas is used in games, data visualisations, and creative coding.

๐Ÿ’ฌ Classroom Discussion Questions

  • 1. What are some real-world applications of the Canvas API?
  • 2. How would you explain the difference between Canvas and SVG?
  • 3. Why is requestAnimationFrame() better than setInterval() for animations?
  • 4. What are some ways you can make Canvas drawings more accessible?
  • 5. How can Canvas be used to create educational tools for Nigerian schools?

๐Ÿš€ Preparation for Module 3

Excellent work on Module 2! You have learned how to draw graphics and animations with Canvas. In Module 3, we will dive into Advanced HTML5 APIs โ€“ Drag and Drop. You will learn how to:

  • Make elements draggable with the draggable attribute.
  • Handle drag events โ€“ dragstart, dragend.
  • Handle drop events โ€“ dragover, drop.
  • Build a drag-and-drop todo list.
  • Drag and drop files.

Before you start Module 3, make sure you can:

  • Create a <canvas> element and draw basic shapes.
  • Use fillStyle and strokeStyle.
  • Understand the basic structure of JavaScript functions.

Keep creating and experimenting โ€“ you are on your way to becoming a professional web developer! ๐Ÿ’ป๐ŸŒŸ


Module 2: Advanced HTML5 APIs โ€“ Canvas • Written with ๐Ÿ’– for young coders in Nigeria and around the world.

4

Module Three

Module 3: Advanced HTML5 APIs โ€“ Drag and Drop

๐Ÿ–ฑ๏ธ Module 3: Advanced HTML5 APIs โ€“ Drag and Drop

Building interactive interfaces by dragging and dropping!

๐Ÿ“– Module Introduction

Welcome to Module 3 of your HTML Level Three journey! In Module 1, you learned about structured data. In Module 2, you learned how to draw graphics and animations with Canvas.

Now, in Module 3, we are going to learn about one of the most interactive and fun features of HTML5 โ€“ the Drag and Drop API!

Drag and drop is exactly what it sounds like โ€“ you click on an element, drag it across the screen, and drop it somewhere else. You have probably used drag and drop before โ€“ maybe when you moved a file on your computer or reordered items in a list.

In this module, you will learn:

  • What the Drag and Drop API is and how it works.
  • How to make elements draggable with the draggable attribute.
  • How to handle drag events โ€“ dragstart, dragend, drag.
  • How to handle drop events โ€“ dragover, drop, dragenter, dragleave.
  • How to transfer data between drag and drop operations.
  • How to drag and drop files from your computer.
  • How to build a drag-and-drop todo list.

Think of this module as learning how to move things around on a webpage. By the end, you will be able to build interactive interfaces that let users rearrange, organise, and upload content simply by dragging and dropping. Let us begin!

๐ŸŽฏ Learning Objectives

By the end of this module, you will be able to:

  • Explain what the Drag and Drop API is and why it is useful.
  • Make elements draggable with the draggable attribute.
  • Handle drag events โ€“ dragstart, dragend, drag.
  • Handle drop events โ€“ dragover, drop, dragenter, dragleave.
  • Use the dataTransfer object to pass data.
  • Drag and drop files from the computer.
  • Build a drag-and-drop todo list.

๐Ÿ“š Warm-up Story: Tundeโ€™s Homework Planner

Tunde was a 13-year-old boy who had a lot of homework to do. He had assignments for Maths, English, Science, and Social Studies. He wanted to organise his tasks by priority โ€“ which ones to do first, second, and third.

Tundeโ€™s big sister, who was a web developer, said, โ€œTunde, you can build a drag-and-drop todo list! You can drag your tasks up and down to reorder them. It will be fun and useful!โ€

Tunde learned how to use the Drag and Drop API. He made each task draggable and created a drop zone where he could drop them. He could drag his tasks to reorder them by priority. His homework planner was a huge success โ€“ he finished his homework faster and even helped his friends organise theirs!

In this module, you will learn exactly what Tunde learned. You will learn how to build interactive, drag-and-drop interfaces that make your web pages fun and useful. Let us get started!

๐Ÿงฉ Main Lessons

Lesson 1: What is the Drag and Drop API?

Definition: The Drag and Drop API is a way to move elements on a web page by clicking, dragging, and releasing them.

Why important: It makes web pages more interactive and user-friendly. Users can rearrange, organise, and upload content easily.

Simple explanation: Drag and drop is like moving toys around on a table โ€“ you pick one up, move it to a new spot, and put it down.

Real-life example: On your computer, you can drag a file from one folder to another โ€“ that is drag and drop.

School example: In a classroom, you might move chairs around to arrange the room โ€“ that is like drag and drop.

Home example: You might move books from one shelf to another โ€“ that is like drag and drop.

Nigerian example: In a Nigerian market, you might move items from one stall to another โ€“ that is like drag and drop.

Illustration:

        Drag and Drop Flow:
        Click on element โ†’ Drag it โ†’ Drop it in a new place
             |              |              |
        "I want to   "I am moving  "I am putting it
        move this"   this element"  down here"
    
๐Ÿ“Œ Mini summary: Drag and drop lets users move elements by clicking, dragging, and releasing. It makes web pages interactive and fun.

Lesson 2: The draggable Attribute โ€“ Making Elements Draggable

Definition: The draggable attribute makes an element draggable โ€“ the user can click and drag it.

Why important: Without draggable, the element cannot be dragged. This is the first step in drag and drop.

Simple explanation: draggable is like putting wheels on a box โ€“ now you can move it.

Code example:

        <div draggable="true">
            I am draggable!
        </div>
    
๐Ÿ“Œ Mini summary: draggable="true" makes an element draggable. This is the first step in drag and drop.

Lesson 3: Drag Events โ€“ dragstart, drag, dragend

Definition: Drag events are triggered during a drag operation. dragstart fires when you start dragging, drag fires repeatedly while dragging, and dragend fires when you stop.

Why important: They let you control what happens during the drag โ€“ like storing data or changing styles.

Simple explanation: These events are like signals โ€“ they tell you when the drag starts, continues, and ends.

Code example:

        <script>
            const dragElement = document.getElementById('dragMe');
            dragElement.addEventListener('dragstart', function(e) {
                console.log('Drag started!');
            });
            dragElement.addEventListener('dragend', function(e) {
                console.log('Drag ended!');
            });
        </script>
    
๐Ÿ“Œ Mini summary: dragstart fires when dragging starts. dragend fires when it ends. drag fires repeatedly while dragging.

Lesson 4: Drop Events โ€“ dragover, drop, dragenter, dragleave

Definition: Drop events are triggered on the drop target โ€“ the place where you want to drop the item.

Why important: They let you control what happens when an item is dragged over or dropped onto a target.

Simple explanation: These events are like signals on the landing pad โ€“ they tell you when something is flying over and when it lands.

Code example:

        <script>
            const dropZone = document.getElementById('dropZone');
            dropZone.addEventListener('dragover', function(e) {
                e.preventDefault(); // allow drop
            });
            dropZone.addEventListener('drop', function(e) {
                e.preventDefault();
                console.log('Item dropped!');
            });
        </script>
    
๐Ÿ“Œ Mini summary: dragover fires when dragging over a drop zone. drop fires when the item is dropped. Always prevent default on dragover to allow drops.

Lesson 5: The dataTransfer Object โ€“ Passing Data

Definition: dataTransfer is an object that stores data during a drag operation. You can set data on the drag start and get it on the drop.

Why important: It lets you pass information from the dragged element to the drop target โ€“ like the ID or text of the item.

Simple explanation: dataTransfer is like a note that you attach to the item. When you drop it, the note is delivered to the drop zone.

Code example:

        // On drag start
        dragElement.addEventListener('dragstart', function(e) {
            e.dataTransfer.setData('text/plain', 'Hello from drag!');
        });

        // On drop
        dropZone.addEventListener('drop', function(e) {
            e.preventDefault();
            const data = e.dataTransfer.getData('text/plain');
            console.log('Received:', data);
        });
    
๐Ÿ“Œ Mini summary: dataTransfer stores data during a drag. Use setData() on drag start and getData() on drop.

Lesson 6: Making a Simple Drag-and-Drop Example

Definition: A simple drag-and-drop example has a draggable element and a drop zone.

Why important: It shows you the basics of how drag and drop works.

Code example:

        <div id="dragMe" draggable="true">Drag me!</div>
        <div id="dropZone">Drop here!</div>

        <script>
            const dragMe = document.getElementById('dragMe');
            const dropZone = document.getElementById('dropZone');

            dragMe.addEventListener('dragstart', function(e) {
                e.dataTransfer.setData('text/plain', 'I was dragged!');
            });

            dropZone.addEventListener('dragover', function(e) {
                e.preventDefault();
            });

            dropZone.addEventListener('drop', function(e) {
                e.preventDefault();
                const data = e.dataTransfer.getData('text/plain');
                dropZone.innerHTML = 'Dropped: ' + data;
            });
        </script>
    
๐Ÿ“Œ Mini summary: A simple drag-and-drop example has a draggable element, a drop zone, and JavaScript to handle the events.

Lesson 7: Visual Feedback โ€“ Styling During Drag

Definition: You can change the style of elements during a drag to give the user visual feedback.

Why important: It tells the user what is happening โ€“ like highlighting the drop zone when something is dragged over it.

Simple explanation: Visual feedback is like changing colour when you hover over a button โ€“ it tells you something is about to happen.

Code example:

        dropZone.addEventListener('dragenter', function(e) {
            dropZone.style.backgroundColor = 'lightblue';
        });

        dropZone.addEventListener('dragleave', function(e) {
            dropZone.style.backgroundColor = 'white';
        });
    
๐Ÿ“Œ Mini summary: Use dragenter and dragleave to provide visual feedback โ€“ like highlighting the drop zone.

Lesson 8: Dragging and Dropping Files

Definition: You can drag files from your computer and drop them onto a web page. This is useful for file uploads.

Why important: It provides a user-friendly way to upload files โ€“ users just drag and drop.

Simple explanation: Dragging files is like dropping a letter into a mailbox โ€“ you put it in, and it gets delivered.

Code example:

        dropZone.addEventListener('drop', function(e) {
            e.preventDefault();
            const files = e.dataTransfer.files;
            for (let file of files) {
                console.log('File:', file.name);
            }
        });
    
๐Ÿ“Œ Mini summary: Use e.dataTransfer.files to access files dropped from the computer. This is great for file uploads.

Lesson 9: Building a Drag-and-Drop Todo List

Definition: A todo list lets users add, complete, and reorder tasks by dragging and dropping.

Why important: It is a practical project that shows you how to use drag and drop in a real-world application.

Simple explanation: A todo list is like a shopping list โ€“ you can add items, cross them off, and reorder them.

Code structure:

  • An array of tasks.
  • Each task is a draggable <li>.
  • A drop zone that reorders tasks.
  • JavaScript to handle drag and drop events.
๐Ÿ“Œ Mini summary: A drag-and-drop todo list lets users reorder tasks by dragging and dropping. It is a great real-world project.

Lesson 10: The dropEffect and effectAllowed Properties

Definition: dropEffect and effectAllowed control the type of drag operation โ€“ like copy, move, or link.

Why important: They let you customise the drag experience and show the user what will happen when they drop.

Simple explanation: These properties are like instructions โ€“ they tell the user if they are moving, copying, or linking the item.

Code example:

        dragElement.addEventListener('dragstart', function(e) {
            e.dataTransfer.effectAllowed = 'move';
        });

        dropZone.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
        });
    
๐Ÿ“Œ Mini summary: effectAllowed sets the allowed operation. dropEffect sets the visual feedback for the drop.

๐Ÿ“– Key Vocabulary

  • Drag: Clicking and moving an element.
  • Drop: Releasing an element into a new location.
  • draggable: An attribute that makes elements draggable.
  • dragstart: Event fired when dragging starts.
  • dragend: Event fired when dragging ends.
  • dragover: Event fired when dragging over a drop zone.
  • drop: Event fired when an item is dropped.
  • dragenter: Event fired when entering a drop zone.
  • dragleave: Event fired when leaving a drop zone.
  • dataTransfer: Object that stores data during a drag.
  • setData: Method to store data.
  • getData: Method to retrieve data.
  • dropEffect: Visual feedback for the drop.
  • effectAllowed: Allowed drag operation.

๐Ÿง  Important Concepts

  • Always prevent default on dragover. If you do not, the drop will not work.
  • dataTransfer is essential. It is how you pass data from the drag to the drop.
  • Visual feedback improves user experience. Highlight drop zones and change cursors.
  • Drag and drop works on touch devices too. You can use touch events for mobile.

๐Ÿชœ Step-by-step Explanations

How to make a simple drag-and-drop:

  1. Add draggable="true" to the element you want to drag.
  2. Add a dragstart event listener to store data in dataTransfer.
  3. Add a drop zone and listen for dragover (prevent default).
  4. Listen for drop on the drop zone to receive the data.

How to drag and drop files:

  1. Create a drop zone.
  2. Listen for dragover and prevent default.
  3. Listen for drop and access e.dataTransfer.files.
  4. Loop through the files and do something with them.

๐ŸŒ Real-life Examples

  • Example 1: Gmail lets you drag and drop files to attach them to emails.
  • Example 2: Trello lets you drag cards from one list to another.
  • Example 3: Google Drive lets you drag and drop files to upload them.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Example 1: A Nigerian e-commerce site could use drag and drop to reorder items in a shopping cart.
  • Example 2: A Nigerian school portal could use drag and drop to let students organise their subjects.
  • Example 3: A Nigerian event website could use drag and drop to let users plan a schedule.

๐ŸŽฎ Fun Examples Children Can Relate To

  • Example 1: A puzzle game where you drag pieces to assemble a picture.
  • Example 2: A classroom seating chart where you drag student names to seats.
  • Example 3: A playlist where you drag songs to reorder them.

๐Ÿ  Everyday Examples

  • Example 1: A to-do list where you drag tasks to reorder them.
  • Example 2: A photo album where you drag photos to rearrange them.
  • Example 3: A calendar where you drag events to different dates.

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง Parent Tips

  • Tip 1: Encourage your child to build a drag-and-drop todo list โ€“ it is a great project.
  • Tip 2: Help them understand that drag and drop makes websites more interactive.
  • Tip 3: Remind them to test their drag-and-drop on different browsers.

๐Ÿ’ก Interesting Facts

  • Fact 1: The Drag and Drop API was introduced in HTML5.
  • Fact 2: Drag and drop works on both desktop and mobile devices.
  • Fact 3: The dataTransfer object can store multiple types of data.

๐Ÿค” Did You Know?

  • Did you know? That you can drag and drop text, images, and even HTML elements?
  • Did you know? That dataTransfer can store files, text, and URLs?
  • Did you know? That you can customise the drag image using setDragImage()?

๐Ÿง  Remember This

  • 1. Use draggable="true" to make elements draggable.
  • 2. Always prevent default on dragover to allow drops.
  • 3. Use dataTransfer to pass data between drag and drop.
  • 4. Use dragenter and dragleave for visual feedback.
  • 5. Drag and drop is great for todo lists, file uploads, and reordering.

โŒ Common Mistakes

  • Mistake 1: Forgetting to add draggable="true" โ€“ the element will not be draggable.
  • Mistake 2: Not preventing default on dragover โ€“ the drop will not work.
  • Mistake 3: Not using dataTransfer โ€“ you will not be able to pass data.
  • Mistake 4: Forgetting to handle dragenter and dragleave โ€“ no visual feedback.
  • Mistake 5: Not testing on different browsers โ€“ drag and drop can behave differently.

โœ… Best Practices

  • Practice 1: Always provide visual feedback โ€“ highlight drop zones.
  • Practice 2: Use dataTransfer to pass all necessary data.
  • Practice 3: Test on multiple browsers and devices.
  • Practice 4: Provide alternative interactions for users who cannot drag.
  • Practice 5: Keep the drag experience smooth and responsive.

๐Ÿ“Š ASCII Illustrations

Drag and Drop Flow

        User clicks on element
              |
              V
        dragstart event fires
              |
              V
        User drags the element
              |
              V
        Element enters drop zone โ†’ dragenter
              |
              V
        Element moves over drop zone โ†’ dragover
              |
              V
        User releases โ†’ drop event fires
              |
              V
        Element is placed in the drop zone ๐ŸŽ‰
    

Event Order

        On the draggable element:
        dragstart โ†’ drag โ†’ dragend

        On the drop target:
        dragenter โ†’ dragover โ†’ (dragleave if you leave) โ†’ drop
    

dataTransfer Flow

        dragstart: setData('text', 'value')
              |
              V
        (drag operation happens)
              |
              V
        drop: getData('text') โ†’ receives 'value'
    

๐Ÿ“‹ Comparison Tables

Drag Events

Event Fires on When it fires
dragstart Draggable element When dragging starts
drag Draggable element Repeatedly while dragging
dragend Draggable element When dragging ends
dragenter Drop target When entering a drop zone
dragover Drop target Repeatedly while over a drop zone
dragleave Drop target When leaving a drop zone
drop Drop target When an item is dropped

dataTransfer Methods

Method What it does Example
setData() Stores data setData('text', 'Hello')
getData() Retrieves data getData('text')
files Accesses dropped files dataTransfer.files
effectAllowed Sets allowed operation effectAllowed = 'move'
dropEffect Sets visual feedback dropEffect = 'move'

๐Ÿ“š End-of-Module Summary

Fantastic work, drag-and-drop master! ๐Ÿ–ฑ๏ธ You have completed Module 3 of HTML Level Three.

Let us recap what you have learned:

  • What the Drag and Drop API is and how it works.
  • How to make elements draggable with draggable="true".
  • How to handle drag events โ€“ dragstart, dragend, drag.
  • How to handle drop events โ€“ dragover, drop, dragenter, dragleave.
  • How to use the dataTransfer object to pass data.
  • How to drag and drop files from the computer.
  • How to build a drag-and-drop todo list.

You now know how to build interactive, user-friendly web pages that let users drag, drop, and organise content. This is a powerful skill used in many modern web applications!

โ“ Frequently Asked Questions

  • Q1: Do I need a special library for drag and drop?
    A: No โ€“ the Drag and Drop API is built into HTML5.
  • Q2: Why is my drop not working?
    A: You probably forgot to prevent default on dragover. Always use e.preventDefault().
  • Q3: Can I drag and drop on mobile?
    A: Yes โ€“ but you may need to use touch events for better mobile support.
  • Q4: What is the dataTransfer object?
    A: It is an object that stores data during a drag operation.
  • Q5: Can I drag and drop images?
    A: Yes โ€“ you can make images draggable and drop them into a drop zone.
  • Q6: What is the difference between effectAllowed and dropEffect?
    A: effectAllowed sets the allowed operation. dropEffect sets the visual feedback.
  • Q7: Can I drag and drop text?
    A: Yes โ€“ you can drag text from one element to another.
  • Q8: What happens if I drop outside a drop zone?
    A: The drop event will not fire. The item will not be dropped.
  • Q9: Can I cancel a drag?
    A: Yes โ€“ you can call e.preventDefault() on dragstart to cancel it.
  • Q10: Is drag and drop accessible?
    A: It can be challenging. Provide alternative interactions for keyboard users.

๐Ÿ”— Matching Exercises

Match the event on the left with its correct description on the right.

Event Description
dragstart A. Fires when dragging over a drop zone
dragend B. Fires when entering a drop zone
dragover C. Fires when dragging starts
drop D. Fires when an item is dropped
dragenter E. Fires when dragging ends
dragleave F. Fires when leaving a drop zone

(Answers: 1-C, 2-E, 3-A, 4-D, 5-B, 6-F)

๐Ÿ“ Scenario-based Exercises

Scenario 1: You are building a todo list app. Users should be able to drag tasks to reorder them.

Question: Write the HTML and JavaScript code for a simple drag-and-drop todo list with three tasks.

Scenario 2: You are building a file upload feature. Users should be able to drag and drop files from their computer to upload them.

Question: Write the HTML and JavaScript code for a drag-and-drop file upload zone.

๐Ÿ‘ฅ Group Activity

Activity: In groups of 3โ€“4 students, build a drag-and-drop colour sorter. You should have:

  • A set of coloured boxes (red, blue, green, yellow).
  • Three drop zones labelled "Warm Colours", "Cool Colours", and "Neutral Colours".
  • Users can drag each colour box into the correct drop zone.
  • When dropped, the box should move into the drop zone.

Present your colour sorter to the class.

๐Ÿง‘โ€๐Ÿ’ป Individual Activity

Activity: Create a page with a simple drag-and-drop where users can reorder a list of their favourite Nigerian foods (e.g., Jollof Rice, Egusi Soup, Suya).

  • Create a list of 5 foods.
  • Make each food item draggable.
  • Allow users to drag and drop to reorder the list.

Save it as food-list.html and open it in your browser.

๐Ÿ› ๏ธ Mini Project

Project: Drag-and-Drop Task Manager

Instructions: Build a complete task manager with drag-and-drop features:

  • โœ… Users can add new tasks.
  • โœ… Users can delete tasks.
  • โœ… Users can drag tasks to reorder them.
  • โœ… Users can drag tasks into different categories (e.g., "To Do", "In Progress", "Done").

Bonus: Add local storage so tasks are saved when the page is refreshed.

๐Ÿ“‹ Practical Assignment

Assignment: Create a page with two columns. The left column has a list of items (like a shopping list). The right column is a drop zone where items can be moved (like a "cart").

  • List at least 5 items in the left column.
  • Make each item draggable.
  • When an item is dropped in the right column, it should move there.
  • Add a "Reset" button that moves all items back to the left column.

Submit your HTML file.

๐Ÿ”‘ Key Takeaways

  • 1. Drag and drop makes web pages interactive and user-friendly.
  • 2. Use draggable="true" to make elements draggable.
  • 3. Always prevent default on dragover to allow drops.
  • 4. Use dataTransfer to pass data between drag and drop.
  • 5. Provide visual feedback to improve user experience.
  • 6. Drag and drop is used in many real-world applications โ€“ from todo lists to file uploads.

๐Ÿ’ฌ Classroom Discussion Questions

  • 1. What are some real-world applications of drag and drop?
  • 2. How would you explain dataTransfer to a 10-year-old?
  • 3. Why is it important to prevent default on dragover?
  • 4. What are some accessibility concerns with drag and drop?
  • 5. How can drag and drop be used in Nigerian e-commerce websites?

๐Ÿš€ Preparation for Module 4

Excellent work on Module 3! You have learned how to build interactive drag-and-drop interfaces. In Module 4, we will dive into Web Components & Custom Elements. You will learn how to:

  • Create your own custom HTML tags like <my-header>.
  • Use the Shadow DOM for encapsulation.
  • Add attributes and properties to custom elements.
  • Build a library of reusable web components.

Before you start Module 4, make sure you can:

  • Make an element draggable with draggable="true".
  • Use dataTransfer to pass data.
  • Handle drop events.

Keep building and experimenting โ€“ you are on your way to becoming a professional web developer! ๐Ÿ’ป๐ŸŒŸ


Module 3: Advanced HTML5 APIs โ€“ Drag and Drop • Written with ๐Ÿ’– for young coders in Nigeria and around the world.

5

Module Four

Module 4: Web Components & Custom Elements

๐Ÿงฉ Module 4: Web Components & Custom Elements

Creating your own custom HTML tags โ€“ just like a professional!

๐Ÿ“– Module Introduction

Welcome to Module 4 of your HTML Level Three journey! In Module 1, you learned about structured data. In Module 2, you learned about Canvas. In Module 3, you learned about Drag and Drop.

Now, in Module 4, we are going to learn about one of the most powerful and modern features of HTML โ€“ Web Components and Custom Elements!

Have you ever wished you could create your own HTML tags? Like <fancy-card> or <my-header>? With Web Components, you can! You can create reusable, custom elements that work just like built-in HTML tags.

In this module, you will learn:

  • What Web Components are and why they are important.
  • How to create Custom Elements with JavaScript.
  • How to use the Shadow DOM to encapsulate styles and markup.
  • How to add attributes and properties to custom elements.
  • How to build a library of reusable components.
  • How to use HTML templates inside custom elements.

Think of this module as learning how to build with LEGO blocks โ€“ you create your own custom pieces, and then you can use them over and over again in different projects. By the end, you will be able to create reusable, professional-grade components that will make you a true web development pro! Let us begin!

๐ŸŽฏ Learning Objectives

By the end of this module, you will be able to:

  • Explain what Web Components are and why they are useful.
  • Create custom HTML elements using the customElements API.
  • Use the Shadow DOM for encapsulation.
  • Add attributes and properties to custom elements.
  • Use HTML templates inside custom elements.
  • Build a library of reusable web components.

๐Ÿ“š Warm-up Story: Nkechiโ€™s Component Library

Nkechi was a 13-year-old girl who loved building websites. She had built many pages for her school, her friends, and her family. But she noticed a problem โ€“ she was writing the same HTML over and over again. Every time she built a new page, she had to write the same header, the same footer, the same cards, and the same buttons.

Nkechiโ€™s big sister, who was a web developer, said, โ€œNkechi, you need to learn about Web Components! You can create your own custom tags, like <my-header> and <fancy-card>. Then you can use them over and over again, just like LEGO blocks.โ€

Nkechi spent a week learning about Web Components. She learned how to create custom elements, use the Shadow DOM, and add attributes. She built a component library with a header, a card, a button, and a footer. Now she could build any website faster and easier than ever before!

In this module, you will learn exactly what Nkechi learned. You will learn how to create reusable, custom HTML components that will make you a faster, smarter developer. Let us get started!

๐Ÿงฉ Main Lessons

Lesson 1: What are Web Components?

Definition: Web Components are a set of web platform APIs that allow you to create reusable, custom HTML elements with their own styles and behaviour.

Why important: They let you reuse code across different projects, making you a faster and more efficient developer.

Simple explanation: Web Components are like LEGO blocks โ€“ you build them once, and then you can use them in many different projects.

Real-life example: A car manufacturer makes parts (like wheels and engines) that can be used in many different car models.

School example: Your teacher uses the same worksheet template for different subjects โ€“ that is like a component.

Home example: You use the same recipe to bake cakes for different occasions โ€“ that is like a component.

Nigerian example: A tailor uses the same pattern to make different styles of clothing โ€“ that is like a component.

Illustration:

        Traditional HTML:
        Write code for every project
              |
              V
        Repeating the same code over and over ๐Ÿ˜ฉ

        Web Components:
        Create a component once
              |
              V
        Use it in any project, anywhere! ๐ŸŽ‰
    
๐Ÿ“Œ Mini summary: Web Components let you create reusable custom HTML elements. They are like LEGO blocks for web development.

Lesson 2: The Three Parts of Web Components

Definition: Web Components have three main parts: Custom Elements, Shadow DOM, and HTML Templates.

Why important: These three parts work together to make components reusable, encapsulated, and powerful.

Simple explanation: Think of a component as a car โ€“ Custom Elements are the car body, Shadow DOM is the interior that you cannot see from outside, and HTML Templates are the blueprint for building the car.

Illustration:

        Web Components
        +----------------------------------+
        |  1. Custom Elements              |
        |     - Create your own tags       |
        |     - Define behaviour           |
        |                                  |
        |  2. Shadow DOM                   |
        |     - Encapsulate styles         |
        |     - Hide internal structure    |
        |                                  |
        |  3. HTML Templates               |
        |     - Define the HTML structure  |
        |     - Reusable code              |
        +----------------------------------+
    
๐Ÿ“Œ Mini summary: Web Components have three parts: Custom Elements (the tag), Shadow DOM (encapsulation), and HTML Templates (the structure).

Lesson 3: Custom Elements โ€“ Creating Your Own Tags

Definition: Custom Elements let you create your own HTML tags using JavaScript.

Why important: It is the main feature of Web Components โ€“ you can define new HTML elements with custom behaviour.

Simple explanation: Custom Elements are like inventing a new word โ€“ you create a new tag, and then you can use it in HTML.

Code example:

        <!-- In HTML -->
        <my-header></my-header>

        <!-- In JavaScript -->
        class MyHeader extends HTMLElement {
            constructor() {
                super();
                this.innerHTML = '<h1>My Custom Header</h1>';
            }
        }
        customElements.define('my-header', MyHeader);
    
๐Ÿ“Œ Mini summary: Custom Elements let you create your own HTML tags. Use customElements.define() to register a new element.

Lesson 4: Naming Custom Elements โ€“ The Rule

Definition: Custom element names must contain a hyphen (e.g., my-header, fancy-card).

Why important: This rule ensures that custom elements do not conflict with built-in HTML tags (which do not have hyphens).

Simple explanation: It is like adding a middle name โ€“ it makes sure everyone knows it is a custom name and not a standard one.

Code example:

        customElements.define('my-header', MyHeader); // โœ… Good
        customElements.define('header', MyHeader);   // โŒ Bad (no hyphen)
    
๐Ÿ“Œ Mini summary: Custom element names must have a hyphen. This prevents conflicts with built-in HTML tags.

Lesson 5: The Shadow DOM โ€“ Encapsulation

Definition: The Shadow DOM is a way to encapsulate (hide) the internal structure and styles of a component from the outside world.

Why important: It prevents your component's styles from conflicting with the rest of the page. It is like having private rooms inside a house.

Simple explanation: The Shadow DOM is like a private room โ€“ what happens inside stays inside, and does not affect the rest of the house.

Code example:

        class MyCard extends HTMLElement {
            constructor() {
                super();
                const shadow = this.attachShadow({ mode: 'open' });
                shadow.innerHTML = `
                    <style>
                        .card {
                            border: 1px solid #ccc;
                            padding: 20px;
                            border-radius: 10px;
                        }
                    </style>
                    <div class="card">
                        <slot></slot>
                    </div>
                `;
            }
        }
        customElements.define('my-card', MyCard);
    
๐Ÿ“Œ Mini summary: The Shadow DOM encapsulates (hides) the internal structure and styles of a component. It prevents conflicts with the rest of the page.

Lesson 6: The slot Element โ€“ Placeholders for Content

Definition: The <slot> element is a placeholder inside a web component where you can insert content from the outside.

Why important: It lets you customise the content of your component โ€“ like putting different text or images inside a card.

Simple explanation: <slot> is like a hole in a puzzle โ€“ you can put different pieces into the hole.

Code example:

        <!-- In JavaScript (inside the component) -->
        shadow.innerHTML = `
            <div class="card">
                <slot name="title">Default Title</slot>
                <slot name="content">Default Content</slot>
            </div>
        `;

        <!-- In HTML (using the component) -->
        <my-card>
            <span slot="title">My Custom Title</span>
            <p slot="content">My custom content goes here!</p>
        </my-card>
    
๐Ÿ“Œ Mini summary: <slot> is a placeholder for content from the outside. It lets you customise your components.

Lesson 7: Adding Attributes to Custom Elements

Definition: You can add attributes to custom elements to pass data into them โ€“ like color, size, or title.

Why important: Attributes let you configure your component โ€“ like changing its colour or text.

Simple explanation: Attributes are like settings for your component โ€“ you can change them to make the component behave differently.

Code example:

        class MyButton extends HTMLElement {
            constructor() {
                super();
                const shadow = this.attachShadow({ mode: 'open' });
                const button = document.createElement('button');
                button.textContent = this.getAttribute('label') || 'Click me!';
                shadow.appendChild(button);
            }
        }
        customElements.define('my-button', MyButton);

        <!-- In HTML -->
        <my-button label="Hello World!"></my-button>
    
๐Ÿ“Œ Mini summary: Attributes let you pass data into custom elements. Use getAttribute() to read them.

Lesson 8: Lifecycle Callbacks โ€“ connectedCallback()

Definition: Lifecycle callbacks are functions that are called at specific times in a component's life. The most important is connectedCallback(), which fires when the element is added to the page.

Why important: It is where you initialise your component โ€“ like setting up event listeners or fetching data.

Simple explanation: connectedCallback() is like a welcome party โ€“ it happens when the component arrives on the page.

Code example:

        class MyComponent extends HTMLElement {
            connectedCallback() {
                console.log('Component added to the page!');
                // Initialisation code here
            }
        }
        customElements.define('my-component', MyComponent);
    
๐Ÿ“Œ Mini summary: connectedCallback() fires when a custom element is added to the page. Use it for initialisation.

Lesson 9: Using HTML Templates Inside Components

Definition: You can use the <template> element to define the HTML structure of your component.

Why important: Templates let you separate the HTML structure from the JavaScript logic, making your code cleaner and more maintainable.

Simple explanation: A template is like a mould โ€“ you use it to create many copies of the same structure.

Code example:

        <!-- In HTML -->
        <template id="my-template">
            <div class="card">
                <h2>Title</h2>
                <p>Content</p>
            </div>
        </template>

        <!-- In JavaScript -->
        class MyCard extends HTMLElement {
            constructor() {
                super();
                const template = document.getElementById('my-template');
                const clone = template.content.cloneNode(true);
                this.attachShadow({ mode: 'open' }).appendChild(clone);
            }
        }
        customElements.define('my-card', MyCard);
    
๐Ÿ“Œ Mini summary: HTML templates define the structure of a component. Use <template> to separate structure from logic.

Lesson 10: Building a Component Library

Definition: A component library is a collection of reusable custom elements that can be used in different projects.

Why important: It saves time and ensures consistency across your projects โ€“ like having a toolbox of ready-to-use parts.

Simple explanation: A component library is like a toolbox โ€“ you have all your tools in one place, and you can use them whenever you need them.

Components you can build:

  • <my-header> โ€“ a reusable header.
  • <my-footer> โ€“ a reusable footer.
  • <fancy-card> โ€“ a styled card.
  • <custom-button> โ€“ a custom button.
  • <user-profile> โ€“ a user profile card.
๐Ÿ“Œ Mini summary: A component library is a collection of reusable custom elements. It saves time and ensures consistency.

๐Ÿ“– Key Vocabulary

  • Web Components: A set of APIs for creating reusable custom elements.
  • Custom Elements: User-defined HTML tags.
  • Shadow DOM: A way to encapsulate the internal structure of a component.
  • HTML Templates: Reusable HTML structures.
  • Slot: A placeholder for content from the outside.
  • customElements.define(): Registers a new custom element.
  • connectedCallback(): A lifecycle callback fired when the element is added to the page.
  • Encapsulation: Hiding internal details from the outside.
  • Component Library: A collection of reusable components.
  • Reusability: Using the same code in multiple places.

๐Ÿง  Important Concepts

  • Encapsulation is key. The Shadow DOM keeps your component's styles and markup private.
  • Reusability saves time. Build once, use everywhere.
  • Components are the future. Modern frameworks (React, Vue, Angular) are built on component concepts.
  • Attributes and slots make components flexible. They let you customise components without changing the code.

๐Ÿชœ Step-by-step Explanations

How to create a simple custom element:

  1. Create a class that extends HTMLElement.
  2. In the constructor(), set up the element.
  3. Use this.attachShadow({ mode: 'open' }) to create a Shadow DOM.
  4. Add content to the Shadow DOM.
  5. Use customElements.define() to register the element.
  6. Use your custom tag in HTML.

How to use a template in a custom element:

  1. Define a <template> in HTML.
  2. In the custom element, get the template using document.getElementById().
  3. Clone the template content using template.content.cloneNode(true).
  4. Append the clone to the Shadow DOM.

๐ŸŒ Real-life Examples

  • Example 1: Google uses Web Components in many of its products.
  • Example 2: GitHub uses custom elements for its UI components.
  • Example 3: Salesforce uses Web Components for its Lightning Design System.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Example 1: A Nigerian fintech company could use Web Components for its payment buttons.
  • Example 2: A Nigerian school portal could use custom elements for student profiles.
  • Example 3: A Nigerian e-commerce site could use Web Components for product cards.

๐ŸŽฎ Fun Examples Children Can Relate To

  • Example 1: A <game-card> component for displaying video game characters.
  • Example 2: A <quiz-question> component for a trivia game.
  • Example 3: A <friend-profile> component for a social network.

๐Ÿ  Everyday Examples

  • Example 1: A <family-member> component for a family tree.
  • Example 2: A <recipe-card> component for a recipe book.
  • Example 3: A <event-card> component for a calendar.

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง Parent Tips

  • Tip 1: Encourage your child to think about components as reusable blocks.
  • Tip 2: Help them understand that Web Components are used by big companies.
  • Tip 3: Remind them that reusing code is a sign of a smart developer.

๐Ÿ’ก Interesting Facts

  • Fact 1: Web Components are supported by all modern browsers.
  • Fact 2: The customElements API was introduced in 2018.
  • Fact 3: Many popular libraries like React and Vue are based on component concepts.

๐Ÿค” Did You Know?

  • Did you know? That you can use Web Components with any framework (or without one)?
  • Did you know? That the Shadow DOM is supported in all modern browsers?
  • Did you know? That you can use <slot> with multiple names for different content?

๐Ÿง  Remember This

  • 1. Custom element names must have a hyphen.
  • 2. Use the Shadow DOM to encapsulate styles and markup.
  • 3. Use <slot> to allow custom content.
  • 4. Use connectedCallback() for initialisation.
  • 5. Build reusable components to save time and effort.

โŒ Common Mistakes

  • Mistake 1: Forgetting the hyphen in the custom element name.
  • Mistake 2: Not using the Shadow DOM โ€“ styles will leak out.
  • Mistake 3: Not cloning the template before appending โ€“ it will only work once.
  • Mistake 4: Using this incorrectly inside the component.
  • Mistake 5: Not calling super() in the constructor.

โœ… Best Practices

  • Practice 1: Always use the Shadow DOM for encapsulation.
  • Practice 2: Use templates to separate structure from logic.
  • Practice 3: Use attributes and slots for customisation.
  • Practice 4: Keep your components focused on one thing.
  • Practice 5: Test your components in different browsers.

๐Ÿ“Š ASCII Illustrations

Web Components Structure

        +------------------------------------------+
        |  Custom Element                          |
        |  +----------------------------------+   |
        |  |  Shadow DOM                      |   |
        |  |  +----------------------------+ |   |
        |  |  |  Template                  | |   |
        |  |  |  
| | | | | | | | | | | |
| | | | | +----------------------------+ | | | | +----------------------------+ | | | | | Styles (encapsulated) | | | | | | .card { ... } | | | | | +----------------------------+ | | | +----------------------------------+ | +------------------------------------------+

Component Lifecycle

        Element is created โ†’ constructor()
              |
              V
        Element is added to the page โ†’ connectedCallback()
              |
              V
        Element is active and visible
              |
              V
        Element is removed from the page โ†’ disconnectedCallback()
    

Using Slots

        <my-card>
        +----------------------------------+
        |  <slot name="title">            |
        |  <slot name="content">          |
        +----------------------------------+
        </my-card>

        When used:
        <my-card>
            <span slot="title">My Title</span>
            <p slot="content">My Content</p>
        </my-card>
    

๐Ÿ“‹ Comparison Tables

Web Components vs. Regular HTML

Feature Regular HTML Web Components
Reusability Low (copy/paste) High (use the same tag anywhere)
Encapsulation None (styles leak) Yes (Shadow DOM)
Customisation Limited Attributes and slots
Maintainability Hard Easy (one place to change)

Lifecycle Callbacks

Callback When it fires What to use it for
constructor() When the element is created Set up the Shadow DOM
connectedCallback() When the element is added to the page Initialisation, event listeners
disconnectedCallback() When the element is removed from the page Clean up
attributeChangedCallback() When an attribute changes React to attribute changes

๐Ÿ“š End-of-Module Summary

Brilliant work, component builder! ๐Ÿงฉ You have completed Module 4 of HTML Level Three.

Let us recap what you have learned:

  • What Web Components are and why they are important.
  • How to create Custom Elements using JavaScript.
  • How to use the Shadow DOM for encapsulation.
  • How to use HTML templates inside components.
  • How to use slots to customise components.
  • How to add attributes to custom elements.
  • How to use lifecycle callbacks like connectedCallback().
  • How to build a component library.

You now know how to create reusable, professional-grade components that will make you a faster, smarter developer. This is a skill used by developers at top companies around the world!

โ“ Frequently Asked Questions

  • Q1: Do I need a framework to use Web Components?
    A: No โ€“ Web Components work in vanilla HTML and JavaScript.
  • Q2: Are Web Components supported in all browsers?
    A: Yes, all modern browsers support Web Components.
  • Q3: What is the Shadow DOM?
    A: It is a way to encapsulate (hide) the internal structure of a component.
  • Q4: Why do custom element names need a hyphen?
    A: To prevent conflicts with built-in HTML tags.
  • Q5: What is a slot?
    A: A placeholder for content from the outside.
  • Q6: What is connectedCallback()?
    A: A lifecycle callback fired when the element is added to the page.
  • Q7: Can I use Web Components with React or Vue?
    A: Yes โ€“ you can use Web Components in any framework.
  • Q8: What is a component library?
    A: A collection of reusable components.
  • Q9: Can I use CSS in the Shadow DOM?
    A: Yes โ€“ you can define styles inside the Shadow DOM.
  • Q10: Are Web Components the same as React components?
    A: No โ€“ React components are different, but Web Components can be used with React.

๐Ÿ”— Matching Exercises

Match the term on the left with its correct description on the right.

Term Description
Custom Element A. A user-defined HTML tag
Shadow DOM B. Encapsulates the internal structure
Slot C. A placeholder for outside content
Template D. Defines reusable HTML structure
connectedCallback E. Fires when the element is added to the page

(Answers: 1-A, 2-B, 3-C, 4-D, 5-E)

๐Ÿ“ Scenario-based Exercises

Scenario 1: You are building a website for a Nigerian school. You want a reusable header component with the school name and logo.

Question: Write the HTML and JavaScript code for a custom <school-header> element.

Scenario 2: You are building a product page for an e-commerce site. You want a reusable product card component that can display different products.

Question: Write the HTML and JavaScript code for a custom <product-card> element with slots for the title, image, and price.

๐Ÿ‘ฅ Group Activity

Activity: In groups of 3โ€“4 students, build a component library together. Each student builds one component:

  • Student 1: <my-header> โ€“ a header with a title and navigation.
  • Student 2: <my-footer> โ€“ a footer with copyright information.
  • Student 3: <fancy-card> โ€“ a card with a title, image, and description.
  • Student 4: <custom-button> โ€“ a button with a label and a click event.

Combine your components into a single page and present it to the class.

๐Ÿง‘โ€๐Ÿ’ป Individual Activity

Activity: Create a custom <user-profile> component. It should display:

  • A profile picture.
  • A name (using an attribute).
  • A bio (using a slot).
  • Styles inside the Shadow DOM.

Save it as profile.html and open it in your browser.

๐Ÿ› ๏ธ Mini Project

Project: Personal Component Library

Instructions: Build a personal component library with at least 5 components:

  • โœ… <my-header> โ€“ a header with a title and navigation.
  • โœ… <my-footer> โ€“ a footer with copyright information.
  • โœ… <fancy-card> โ€“ a card with slots for title, image, and content.
  • โœ… <custom-button> โ€“ a button with a label attribute.
  • โœ… <user-profile> โ€“ a user profile with name and bio.

Bonus: Add a <testimonial> component with a quote and author.

๐Ÿ“‹ Practical Assignment

Assignment: Create a page that uses at least 3 custom components. Your page should include:

  • A <my-header> component for the header.
  • A <my-card> component for displaying information.
  • A <my-footer> component for the footer.

Each component should have its own Shadow DOM and styles. Submit your HTML file with all components defined in a <script> tag.

๐Ÿ”‘ Key Takeaways

  • 1. Web Components let you create reusable custom HTML elements.
  • 2. Use the Shadow DOM to encapsulate styles and markup.
  • 3. Use customElements.define() to register a custom element.
  • 4. Use <slot> to allow custom content.
  • 5. Use connectedCallback() for initialisation.
  • 6. Build a component library to save time and ensure consistency.

๐Ÿ’ฌ Classroom Discussion Questions

  • 1. Why do you think reusability is important in web development?
  • 2. How would you explain the Shadow DOM to a 10-year-old?
  • 3. What are some components you would like to build for your own projects?
  • 4. How can Web Components help Nigerian businesses?
  • 5. What is the difference between a Web Component and a React component?

๐Ÿš€ Preparation for Module 5

Excellent work on Module 4! You have learned how to create reusable custom HTML components. In Module 5, we will dive into HTML Templates & Slots. You will learn how to:

  • Use <template> to define reusable HTML structures.
  • Use <slot> to create placeholders for content.
  • Use named slots for different types of content.
  • Build a template-based gallery.

Before you start Module 5, make sure you can:

  • Create a custom element with customElements.define().
  • Use the Shadow DOM.
  • Understand the concept of encapsulation.

Keep building and experimenting โ€“ you are on your way to becoming a professional web developer! ๐Ÿ’ป๐ŸŒŸ


Module 4: Web Components & Custom Elements • Written with ๐Ÿ’– for young coders in Nigeria and around the world.

6

Module Five

Module 5: HTML Templates & Slots

๐Ÿ“„ Module 5: HTML Templates & Slots

Reusing HTML code like a pro โ€“ with templates and slots!

๐Ÿ“– Module Introduction

Welcome to Module 5 of your HTML Level Three journey! In Module 1, you learned about structured data. In Module 2, you learned about Canvas. In Module 3, you learned about Drag and Drop. In Module 4, you learned about Web Components and Custom Elements.

Now, in Module 5, we are going to learn about two powerful features that make Web Components even better: HTML Templates and Slots!

Have you ever wanted to write a piece of HTML once and use it many times? That is exactly what templates do! They let you define reusable HTML structures that you can clone and use anywhere.

And slots? Slots are like holes in your templates where you can insert different content each time you use the template. They make your components flexible and customisable.

In this module, you will learn:

  • What the <template> element is and how to use it.
  • How to clone templates with JavaScript.
  • What the <slot> element is and how to use it.
  • How to use named slots for different content.
  • How to build a template-based gallery.
  • How to use templates inside Web Components.

Think of this module as learning how to make stamps. Once you have a stamp (template), you can use it to create as many copies as you want โ€“ and each copy can be a little different (using slots). By the end, you will be able to build reusable, flexible, and efficient web pages. Let us begin!

๐ŸŽฏ Learning Objectives

By the end of this module, you will be able to:

  • Explain what <template> is and why it is useful.
  • Use <template> to define reusable HTML structures.
  • Clone templates using JavaScript.
  • Explain what <slot> is and why it is useful.
  • Use <slot> to create placeholders for content.
  • Use named slots for different types of content.
  • Build a template-based gallery.
  • Use templates inside Web Components.

๐Ÿ“š Warm-up Story: Chidiโ€™s Photo Gallery

Chidi was a 13-year-old boy who loved taking photos. He had hundreds of photos from his trips around Nigeria โ€“ Lagos, Abuja, Calabar, and many more. He wanted to create a photo gallery on his website to share his photos with friends and family.

Chidi started by writing HTML for each photo โ€“ a <div> with an image and a caption. But after writing the same code for the 10th photo, he was tired. He thought, โ€œThere must be an easier way!โ€

Chidiโ€™s big sister, who was a web developer, said, โ€œChidi, you need to learn about HTML templates! You can write the structure once, and then use it to create as many photos as you want โ€“ just like a stamp!โ€

Chidi learned how to use <template> and <slot>. He created a template for a photo card, and then used JavaScript to clone it for each photo. He even used slots to insert different images and captions. His photo gallery was built in minutes โ€“ and it looked amazing!

In this module, you will learn exactly what Chidi learned. You will learn how to use templates and slots to build reusable, efficient, and flexible web pages. Let us get started!

๐Ÿงฉ Main Lessons

Lesson 1: What is the <template> Element?

Definition: The <template> element is a container for HTML that is not displayed until you use it with JavaScript.

Why important: It lets you define reusable HTML structures that you can clone and use many times โ€“ like a stamp for your web page.

Simple explanation: <template> is like a mould for making cookies. You create the mould once, and then you can make as many cookies as you want.

Real-life example: A factory makes a mould for a toy. They use the mould to create thousands of identical toys.

School example: Your teacher has a worksheet template. She prints copies for all the students.

Home example: You have a recipe for cake. You use the same recipe to bake cakes for different occasions.

Nigerian example: A tailor has a pattern for a shirt. He uses the same pattern to make shirts for many customers.

Code example:

        <template id="my-template">
            <div class="card">
                <h2>Title</h2>
                <p>Content</p>
            </div>
        </template>

        <!-- The template is not displayed on the page -->
    
๐Ÿ“Œ Mini summary: <template> defines reusable HTML structures. The content is not displayed until you use it with JavaScript.

Lesson 2: Why Templates are Important

Definition: Templates help you avoid repetition by letting you write HTML once and reuse it many times.

Why important: They make your code cleaner, easier to maintain, and more efficient.

Simple explanation: Templates are like shortcuts โ€“ instead of writing the same code over and over, you write it once and use it everywhere.

Real-life example: A restaurant has a menu. They print the same menu for all customers โ€“ they do not write a new menu for every customer.

School example: Your school has a uniform. All students wear the same uniform โ€“ the uniform is like a template.

Home example: Your family has a weekly meal plan. You use the same plan every week.

Nigerian example: A Nigerian market has stalls with the same structure โ€“ each stall is like a template.

Illustration:

        Without templates:
        Write code โ†’ copy โ†’ paste โ†’ copy โ†’ paste โ†’ copy โ†’ paste ๐Ÿ˜ฉ

        With templates:
        Write code once โ†’ use it many times! ๐ŸŽ‰
    
๐Ÿ“Œ Mini summary: Templates save time and effort by letting you reuse HTML code. They make your code cleaner and easier to maintain.

Lesson 3: Cloning a Template with JavaScript

Definition: You use JavaScript to clone (copy) a template and add it to the page.

Why important: Cloning is how you actually use the template โ€“ it creates a copy that you can insert into the page.

Simple explanation: Cloning a template is like photocopying a document โ€“ you get an exact copy.

Code example:

        <!-- HTML -->
        <template id="card-template">
            <div class="card">
                <h2>Hello!</h2>
            </div>
        </template>

        <!-- JavaScript -->
        <script>
            const template = document.getElementById('card-template');
            const clone = template.content.cloneNode(true);
            document.body.appendChild(clone);
        </script>
    
๐Ÿ“Œ Mini summary: Use template.content.cloneNode(true) to clone a template. Then append the clone to the page.

Lesson 4: The content Property โ€“ Inside the Template

Definition: The content property gives you access to the HTML inside the template.

Why important: You need to access content to clone the template's inner HTML.

Simple explanation: content is like the inside of a box โ€“ it holds all the good stuff.

Code example:

        const template = document.getElementById('my-template');
        const clone = template.content.cloneNode(true);
        // clone now contains the HTML from inside the template
    
๐Ÿ“Œ Mini summary: template.content gives you the HTML inside the template. Use it to clone the template.

Lesson 5: What is the <slot> Element?

Definition: The <slot> element is a placeholder inside a template or web component where you can insert different content.

Why important: It makes your templates flexible โ€“ you can use the same template but put different content in the slots.

Simple explanation: <slot> is like a hole in a puzzle โ€“ you can put different pieces into the hole each time.

Real-life example: A picture frame has a slot where you can put different pictures.

School example: A test paper has blanks where you write different answers.

Home example: A recipe book has slots for different ingredients โ€“ you can put different ingredients in each recipe.

Nigerian example: A market stall has a slot for different products โ€“ you can put different items in the same stall.

Code example:

        <template id="card-template">
            <div class="card">
                <slot name="title">Default Title</slot>
                <slot name="content">Default Content</slot>
            </div>
        </template>
    
๐Ÿ“Œ Mini summary: <slot> is a placeholder for content. It makes templates flexible and reusable.

Lesson 6: Named Slots โ€“ Different Placeholders for Different Content

Definition: Named slots have a name attribute. They let you put different content into different slots.

Why important: They give you fine control over where content goes โ€“ like having different sections in a card.

Simple explanation: Named slots are like labelled boxes โ€“ you put the right thing in the right box.

Code example:

        <template id="card-template">
            <div class="card">
                <slot name="title">Default Title</slot>
                <slot name="image"></slot>
                <slot name="description">Default Description</slot>
            </div>
        </template>

        <!-- Using the template -->
        <my-card>
            <span slot="title">My Photo</span>
            <img slot="image" src="photo.jpg" />
            <p slot="description">This is my favourite photo.</p>
        </my-card>
    
๐Ÿ“Œ Mini summary: Named slots have a name attribute. They let you put different content into different slots.

Lesson 7: Default Content in Slots

Definition: You can put default content inside a slot. This content is displayed if nothing is provided from the outside.

Why important: It gives your component a fallback โ€“ if the user does not provide content, they still see something.

Simple explanation: Default content is like a backup plan โ€“ if you do not bring your own food, you get the default meal.

Code example:

        <template id="card-template">
            <div class="card">
                <slot name="title">My Default Title</slot>
                <slot name="content">This is the default content.</slot>
            </div>
        </template>
    
๐Ÿ“Œ Mini summary: Default content in slots is displayed when no content is provided from the outside. It is like a backup plan.

Lesson 8: Using Templates Inside Web Components

Definition: Templates are often used inside Web Components to define the component's HTML structure.

Why important: It separates the component's structure from its logic, making the code cleaner and more maintainable.

Simple explanation: Using a template inside a web component is like using a blueprint to build a house โ€“ the blueprint tells you what to build.

Code example:

        <template id="my-component">
            <div class="component">
                <slot name="header">Header</slot>
                <slot name="body">Body</slot>
            </div>
        </template>

        <script>
            class MyComponent extends HTMLElement {
                constructor() {
                    super();
                    const template = document.getElementById('my-component');
                    const clone = template.content.cloneNode(true);
                    this.attachShadow({ mode: 'open' }).appendChild(clone);
                }
            }
            customElements.define('my-component', MyComponent);
        </script>
    
๐Ÿ“Œ Mini summary: Use templates inside Web Components to define the HTML structure. It separates structure from logic.

Lesson 9: Building a Template-Based Gallery

Definition: A template-based gallery uses a template to create many photo cards with different images and captions.

Why important: It is a practical project that shows you how templates and slots work together in a real-world application.

Simple explanation: A gallery is like a wall where you hang many pictures. The template is the frame โ€“ you use the same frame for all pictures.

Code structure:

  • A <template> for a photo card with slots for image and caption.
  • JavaScript that loops through an array of photos and clones the template for each one.
  • Each clone gets a different image and caption.
๐Ÿ“Œ Mini summary: A template-based gallery uses templates to create many photo cards. It is a great way to practice templates and slots.

๐Ÿ“– Key Vocabulary

  • Template: A reusable HTML structure.
  • Clone: To make a copy of something.
  • Content: The HTML inside a template.
  • Slot: A placeholder for content.
  • Named Slot: A slot with a name attribute.
  • Default Content: Content shown when no content is provided.
  • Reusability: Using the same code in multiple places.
  • Encapsulation: Hiding internal details.
  • Web Component: A reusable custom HTML element.

๐Ÿง  Important Concepts

  • Templates are invisible. They do not display anything until you clone and append them.
  • Slots make templates flexible. They let you insert different content into the same template.
  • Named slots organise content. They tell you where to put different pieces of content.
  • Templates + Web Components = powerful. Together, they let you build reusable, encapsulated components.

๐Ÿชœ Step-by-step Explanations

How to create and use a template:

  1. Define a <template> with an id.
  2. Add HTML inside the template.
  3. In JavaScript, get the template using document.getElementById().
  4. Clone the template using template.content.cloneNode(true).
  5. Append the clone to the page.

How to use slots in a template:

  1. Inside the template, add <slot name="name">.
  2. When using the template, add elements with slot="name".
  3. The content will be inserted into the slot.

๐ŸŒ Real-life Examples

  • Example 1: A news website uses templates to display articles.
  • Example 2: An e-commerce site uses templates for product cards.
  • Example 3: A social media site uses templates for posts.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Example 1: A Nigerian news site uses templates for news articles.
  • Example 2: A Nigerian e-commerce site uses templates for product listings.
  • Example 3: A Nigerian school website uses templates for student profiles.

๐ŸŽฎ Fun Examples Children Can Relate To

  • Example 1: A game card template for a card game.
  • Example 2: A character template for a role-playing game.
  • Example 3: A recipe card template for a cookbook.

๐Ÿ  Everyday Examples

  • Example 1: A photo album template for family photos.
  • Example 2: A birthday card template for different people.
  • Example 3: A to-do list template for daily tasks.

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง Parent Tips

  • Tip 1: Encourage your child to think about templates as reusable blueprints.
  • Tip 2: Help them understand that templates save time and reduce repetition.
  • Tip 3: Remind them that slots make templates flexible and powerful.

๐Ÿ’ก Interesting Facts

  • Fact 1: The <template> element was introduced in HTML5.
  • Fact 2: Templates are supported in all modern browsers.
  • Fact 3: Slots are a key feature of Web Components.

๐Ÿค” Did You Know?

  • Did you know? That templates can contain styles, scripts, and even other templates?
  • Did you know? That slots can have default content that shows when nothing is provided?
  • Did you know? That templates are used by many popular websites to display dynamic content?

๐Ÿง  Remember This

  • 1. Templates define reusable HTML structures.
  • 2. Use cloneNode(true) to copy a template.
  • 3. Slots are placeholders for content.
  • 4. Named slots let you organise different content.
  • 5. Templates + Slots = flexible, reusable components.

โŒ Common Mistakes

  • Mistake 1: Forgetting to use cloneNode(true) โ€“ you need a deep clone.
  • Mistake 2: Not giving the template an id โ€“ you cannot find it.
  • Mistake 3: Using template.innerHTML instead of template.content.
  • Mistake 4: Not using the correct slot name โ€“ the content will not appear.
  • Mistake 5: Forgetting to append the clone to the page.

โœ… Best Practices

  • Practice 1: Always give templates a unique id.
  • Practice 2: Use cloneNode(true) for deep cloning.
  • Practice 3: Use named slots for different content.
  • Practice 4: Use default content in slots for fallbacks.
  • Practice 5: Use templates inside Web Components for clean code.

๐Ÿ“Š ASCII Illustrations

Template Structure

        <template id="card">
        +----------------------------------+
        |  <div class="card">             |
        |    <slot name="title">Title</slot>|
        |    <slot name="content">Content</slot>|
        |  </div>                          |
        +----------------------------------+
        </template>
    

Clone Flow

        Template (invisible)
              |
              V
        JavaScript clones the template
              |
              V
        Clone is appended to the page              |
              V
        Content appears on the page! ๐ŸŽ‰
    

Slot Usage

        <my-card>
        +----------------------------------+
        |  <span slot="title">My Title</span>|
        |  <p slot="content">My Content</p> |
        +----------------------------------+
        </my-card>

        The slots get filled with the provided content.
    

๐Ÿ“‹ Comparison Tables

Template vs. Regular HTML

Feature Regular HTML Template
Displayed immediately Yes No (invisible until used)
Reusable No (copy/paste) Yes (clone)
Can contain slots No Yes
Best for Static content Dynamic content

Slot Types

Slot Type How it works When to use
Unnamed slot One placeholder for all content Simple content
Named slot Multiple placeholders with names Complex content with sections
Default content Content shown when slot is empty Fallback content

๐Ÿ“š End-of-Module Summary

Fantastic work, template master! ๐Ÿ“„ You have completed Module 5 of HTML Level Three.

Let us recap what you have learned:

  • What the <template> element is and how to use it.
  • How to clone templates using JavaScript.
  • What the <slot> element is and how to use it.
  • How to use named slots for different content.
  • How to use default content in slots.
  • How to use templates inside Web Components.
  • How to build a template-based gallery.

You now know how to build reusable, flexible, and efficient web pages using templates and slots. This is a professional skill used by developers at top companies around the world!

โ“ Frequently Asked Questions

  • Q1: What is the difference between a template and a regular div?
    A: A template is invisible until you use it. A div is visible immediately.
  • Q2: Why do I need to clone a template?
    A: Cloning creates a copy that you can use. If you use the template directly, it will only work once.
  • Q3: What is a slot?
    A: A slot is a placeholder for content inside a template or web component.
  • Q4: What is a named slot?
    A: A slot with a name attribute that lets you put different content in different slots.
  • Q5: Can I use templates without JavaScript?
    A: No โ€“ templates require JavaScript to clone and append them.
  • Q6: Can I use slots in regular HTML?
    A: Slots only work inside Web Components and templates.
  • Q7: What is default content in a slot?
    A: Content that is shown when nothing is provided from the outside.
  • Q8: Can I have multiple slots in one template?
    A: Yes โ€“ you can have many slots with different names.
  • Q9: Are templates supported in all browsers?
    A: Yes, all modern browsers support templates.
  • Q10: What is the content property?
    A: It gives you access to the HTML inside a template.

๐Ÿ”— Matching Exercises

Match the term on the left with its correct description on the right.

Term Description
<template> A. A placeholder for content
<slot> B. A reusable HTML structure
Named slot C. Content shown when no content is provided
Default content D. A slot with a name attribute
cloneNode() E. Makes a copy of a template

(Answers: 1-B, 2-A, 3-D, 4-C, 5-E)

๐Ÿ“ Scenario-based Exercises

Scenario 1: You are building a recipe website. You want to display many recipes using the same structure โ€“ each recipe has a title, an image, and a description.

Question: Write the HTML and JavaScript code for a recipe template with slots for title, image, and description.

Scenario 2: You are building a product page for an e-commerce site. You want to use a template to display product cards with different products.

Question: Write the HTML and JavaScript code for a product template with named slots for product name, price, and image.

๐Ÿ‘ฅ Group Activity

Activity: In groups of 3โ€“4 students, build a template-based gallery together. Each student contributes:

  • Student 1: Designs the template for a photo card (with slots for image, title, and description).
  • Student 2: Writes the JavaScript to clone the template for each photo.
  • Student 3: Provides the data (array of photos with titles and descriptions).
  • Student 4: Adds styling and presents the gallery.

Present your gallery to the class.

๐Ÿง‘โ€๐Ÿ’ป Individual Activity

Activity: Create a page with a template for a "friend profile" card. Each card should show:

  • A profile picture (using an image slot).
  • A name (using a text slot).
  • A short bio (using a text slot).

Use JavaScript to create at least 3 friend profiles using the template. Save it as friends.html and open it in your browser.

๐Ÿ› ๏ธ Mini Project

Project: Template-Based Recipe Gallery

Instructions: Build a recipe gallery using templates. Your gallery should include:

  • โœ… A template for a recipe card with slots for title, image, description, and cooking time.
  • โœ… At least 5 recipes with different data.
  • โœ… JavaScript that loops through the recipes and clones the template for each one.
  • โœ… Each recipe card should be appended to the page.

Bonus: Add a "search" feature that filters recipes by title.

๐Ÿ“‹ Practical Assignment

Assignment: Create a page that displays a list of Nigerian cities using a template. Each city card should show:

  • The city name.
  • A short description.
  • A famous landmark.

Use a template with slots for each piece of data. Use JavaScript to create at least 5 city cards. Submit your HTML file.

๐Ÿ”‘ Key Takeaways

  • 1. Templates define reusable HTML structures.
  • 2. Use cloneNode(true) to clone a template.
  • 3. Slots are placeholders for content.
  • 4. Named slots let you organise different content.
  • 5. Default content is shown when no content is provided.
  • 6. Templates + Slots = flexible, reusable components.

๐Ÿ’ฌ Classroom Discussion Questions

  • 1. Why do you think templates are important for web development?
  • 2. How would you explain slots to a 10-year-old?
  • 3. What are some other uses for templates besides galleries?
  • 4. How can templates help Nigerian businesses build websites faster?
  • 5. What is the difference between a template and a web component?

๐Ÿš€ Preparation for Module 6

Excellent work on Module 5! You have learned how to use templates and slots to build reusable, flexible web pages. In Module 6, we will dive into Advanced Forms & Inputs. You will learn how to:

  • Use <datalist> for autocomplete suggestions.
  • Use inputmode to control mobile keyboards.
  • Use autocomplete for form auto-fill.
  • Use form attributes to link inputs outside the form.
  • Use novalidate to turn off validation.

Before you start Module 6, make sure you can:

  • Create a template with <template>.
  • Clone a template with cloneNode(true).
  • Use slots inside a template.

Keep building and experimenting โ€“ you are on your way to becoming a professional web developer! ๐Ÿ’ป๐ŸŒŸ


Module 5: HTML Templates & Slots • Written with ๐Ÿ’– for young coders in Nigeria and around the world.

7

Module Six

Module 6: Advanced Forms & Inputs

๐Ÿ“ Module 6: Advanced Forms & Inputs

Building smarter, more user-friendly forms with advanced techniques!

๐Ÿ“– Module Introduction

Welcome to Module 6 of your HTML Level Three journey! In Module 1, you learned about structured data. In Module 2, you learned about Canvas. In Module 3, you learned about Drag and Drop. In Module 4, you learned about Web Components. In Module 5, you learned about Templates and Slots.

Now, in Module 6, we are going to revisit one of the most important parts of any website: forms! You already know the basics of forms from Level Two. Now we are going to go deeper and learn advanced techniques that will make your forms smarter, easier to use, and more accessible.

In this module, you will learn:

  • How to use <datalist> for autocomplete suggestions.
  • How to use inputmode to control the keyboard on mobile devices.
  • How to use autocomplete to help browsers auto-fill forms.
  • How to use form attributes to link inputs outside the <form> tag.
  • How to use novalidate to turn off browser validation.
  • How to use the enterkeyhint attribute to customise the Enter key.

Think of this module as adding superpowers to your forms. By the end, you will be able to build forms that are fast, intuitive, and accessible โ€“ just like the ones used by top tech companies. Let us begin!

๐ŸŽฏ Learning Objectives

By the end of this module, you will be able to:

  • Use <datalist> to provide autocomplete suggestions.
  • Use inputmode to control mobile keyboards.
  • Use autocomplete for form auto-fill.
  • Use form attributes to link inputs outside the form.
  • Use novalidate to turn off validation.
  • Use enterkeyhint to customise the Enter key.
  • Build an advanced contact form with all these features.

๐Ÿ“š Warm-up Story: Amaraโ€™s Contact Form

Amara was a 13-year-old girl who loved helping people. She had built a website for her community group, and she wanted to add a contact form so people could send messages easily.

Amara built a basic form with name, email, and message fields. It worked, but it was not very user-friendly. People had to type their full email address every time, and on mobile phones, the keyboard was not optimised for typing emails or phone numbers.

Amaraโ€™s big sister, who was a web developer, said, โ€œAmara, you need to learn advanced form techniques! You can add autocomplete suggestions, control the mobile keyboard, and make your form smarter and faster to use.โ€

Amara learned about <datalist>, inputmode, and autocomplete. She added autocomplete suggestions for email addresses, changed the keyboard for phone numbers, and added auto-fill for common fields. Her contact form became a joy to use โ€“ people loved how fast and easy it was!

In this module, you will learn exactly what Amara learned. You will learn how to build smart, user-friendly, and advanced forms. Let us get started!

๐Ÿงฉ Main Lessons

Lesson 1: The <datalist> Element โ€“ Autocomplete Suggestions

Definition: <datalist> provides a list of autocomplete suggestions for an input field.

Why important: It helps users type faster by showing suggestions as they type โ€“ like when you type in a search box.

Simple explanation: <datalist> is like a helpful friend who suggests what you might be trying to type.

Real-life example: When you type in Google's search box, it suggests search terms โ€“ that is like a datalist.

School example: A spelling test with a list of possible words โ€“ that is like a datalist.

Home example: A shopping list with common items โ€“ you can pick from the list.

Nigerian example: A Nigerian website with a list of states โ€“ when you type "La", it suggests "Lagos".

Code example:

        <label for="city">City:</label>
        <input type="text" id="city" name="city" list="cities" />
        <datalist id="cities">
            <option value="Lagos" />
            <option value="Abuja" />
            <option value="Kano" />
            <option value="Ibadan" />
            <option value="Port Harcourt" />
        </datalist>
    
๐Ÿ“Œ Mini summary: <datalist> provides autocomplete suggestions. It makes typing faster and easier.

Lesson 2: The list Attribute โ€“ Connecting to a Datalist

Definition: The list attribute connects an input field to a <datalist> by matching the id of the datalist.

Why important: It is how the input knows which datalist to use for suggestions.

Simple explanation: list is like a name tag that says "Use this list of suggestions".

Code example:

        <input type="text" list="my-suggestions" />
        <datalist id="my-suggestions">
            <option value="Option 1" />
            <option value="Option 2" />
        </datalist>
    
๐Ÿ“Œ Mini summary: The list attribute connects an input to a datalist. The id of the datalist must match the list value.

Lesson 3: The inputmode Attribute โ€“ Controlling the Keyboard

Definition: inputmode tells mobile browsers what type of keyboard to show โ€“ like a number pad or a full keyboard.

Why important: It makes typing easier on mobile devices by showing the right keyboard for the input type.

Simple explanation: inputmode is like choosing the right tool for the job โ€“ you use a screwdriver for screws, and a hammer for nails.

Real-life example: On a phone, when you tap a number field, the number pad appears โ€“ that is inputmode at work.

School example: A calculator app shows a number pad โ€“ that is like inputmode.

Home example: When you enter your phone number on a website, the number pad appears โ€“ that is inputmode.

Nigerian example: A Nigerian bank app shows a number pad when you enter your account number โ€“ that is inputmode.

Code example:

        <label for="phone">Phone:</label>
        <input type="tel" id="phone" name="phone" inputmode="numeric" />

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" inputmode="email" />

        <label for="url">Website:</label>
        <input type="url" id="url" name="url" inputmode="url" />
    
๐Ÿ“Œ Mini summary: inputmode controls the keyboard that appears on mobile devices. Use numeric, email, or url for the right keyboard.

Lesson 4: The autocomplete Attribute โ€“ Auto-Fill

Definition: autocomplete tells the browser whether to auto-fill the field with saved user data.

Why important: It saves users time by automatically filling in common fields like name, email, and address.

Simple explanation: autocomplete is like a memory โ€“ the browser remembers what you typed before and fills it in for you.

Real-life example: When you fill out a form, the browser offers to auto-fill your name and address โ€“ that is autocomplete.

School example: A test paper with your name already filled in โ€“ that is like autocomplete.

Home example: A shopping list that remembers what you bought last week โ€“ that is like autocomplete.

Nigerian example: A Nigerian bank form that auto-fills your BVN โ€“ that is autocomplete.

Common values:

  • name โ€“ full name
  • given-name โ€“ first name
  • family-name โ€“ last name
  • email โ€“ email address
  • tel โ€“ phone number
  • address โ€“ full address
  • country โ€“ country
  • postal-code โ€“ zip code
  • off โ€“ turn off autocomplete

Code example:

        <label for="name">Full Name:</label>
        <input type="text" id="name" name="name" autocomplete="name" />

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" autocomplete="email" />

        <label for="phone">Phone:</label>
        <input type="tel" id="phone" name="phone" autocomplete="tel" />
    
๐Ÿ“Œ Mini summary: autocomplete tells the browser to auto-fill fields. Use values like name, email, and tel.

Lesson 5: The form Attribute โ€“ Linking Inputs Outside the Form

Definition: The form attribute lets you link an input to a form even if the input is outside the <form> tag.

Why important: It gives you more flexibility in designing your page layout โ€“ you can put inputs anywhere.

Simple explanation: form is like a remote control โ€“ it lets you control the form from anywhere on the page.

Code example:

        <form id="myForm" action="/submit" method="POST">
            <button type="submit">Submit</button>
        </form>

        <!-- This input is OUTSIDE the form, but linked to it -->
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" form="myForm" />
    
๐Ÿ“Œ Mini summary: The form attribute links an input to a form, even if the input is outside the form.

Lesson 6: The formaction Attribute โ€“ Custom Submit URL

Definition: formaction lets you override the form's action URL for a specific button.

Why important: It lets you have multiple submit buttons that send data to different URLs.

Simple explanation: formaction is like having different mailing addresses for different purposes โ€“ you send the form to one address or another.

Code example:

        <form action="/default" method="POST">
            <input type="text" name="data" />
            <button type="submit">Send to Default</button>
            <button type="submit" formaction="/special">Send to Special</button>
        </form>
    
๐Ÿ“Œ Mini summary: formaction lets you override the form's action for a specific button.

Lesson 7: The formenctype Attribute โ€“ Custom Encoding

Definition: formenctype overrides the form's enctype (encoding type) for a specific button.

Why important: It lets you control how form data is encoded โ€“ useful for file uploads.

Code example:

        <form action="/upload" method="POST" enctype="application/x-www-form-urlencoded">
            <input type="file" name="file" />
            <button type="submit" formenctype="multipart/form-data">Upload File</button>
        </form>
    
๐Ÿ“Œ Mini summary: formenctype overrides the form's encoding type for a specific button โ€“ useful for file uploads.

Lesson 8: The formmethod Attribute โ€“ Custom Method

Definition: formmethod overrides the form's method (GET or POST) for a specific button.

Why important: It lets you have different submission methods for different buttons.

Code example:

        <form action="/search" method="GET">
            <input type="text" name="query" />
            <button type="submit">Search (GET)</button>
            <button type="submit" formmethod="POST" formaction="/save">Save (POST)</button>
        </form>
    
๐Ÿ“Œ Mini summary: formmethod overrides the form's method (GET or POST) for a specific button.

Lesson 9: The formnovalidate Attribute โ€“ Turn Off Validation

Definition: formnovalidate turns off browser validation when a specific button is clicked.

Why important: It lets you submit the form without validation โ€“ useful for save buttons or draft submissions.

Code example:

        <form action="/submit" method="POST">
            <input type="text" name="data" required />
            <button type="submit">Submit (with validation)</button>
            <button type="submit" formnovalidate>Save Draft (no validation)</button>
        </form>
    
๐Ÿ“Œ Mini summary: formnovalidate turns off validation for a specific button โ€“ useful for draft submissions.

Lesson 10: The novalidate Attribute โ€“ Turn Off Validation for the Whole Form

Definition: novalidate turns off all browser validation for the entire form.

Why important: It gives you full control over validation โ€“ you can use your own custom validation with JavaScript.

Code example:

        <form action="/submit" method="POST" novalidate>
            <input type="text" name="data" required />
            <button type="submit">Submit (no validation)</button>
        </form>
    
๐Ÿ“Œ Mini summary: novalidate turns off all validation for the whole form โ€“ you can use your own validation.

Lesson 11: The enterkeyhint Attribute โ€“ Customising the Enter Key

Definition: enterkeyhint customises the text on the Enter key on mobile keyboards (e.g., "Search", "Send", "Next").

Why important: It improves the user experience by telling users what will happen when they press Enter.

Common values:

  • enter โ€“ default
  • done โ€“ done
  • go โ€“ go
  • next โ€“ next
  • previous โ€“ previous
  • search โ€“ search
  • send โ€“ send

Code example:

        <input type="text" enterkeyhint="search" placeholder="Type to search..." />
        <input type="text" enterkeyhint="send" placeholder="Type your message..." />
    
๐Ÿ“Œ Mini summary: enterkeyhint customises the text on the Enter key on mobile keyboards.

๐Ÿ“– Key Vocabulary

  • Datalist: A list of autocomplete suggestions.
  • inputmode: Controls the mobile keyboard.
  • autocomplete: Enables browser auto-fill.
  • form attribute: Links an input to a form.
  • formaction: Overrides the form action.
  • formmethod: Overrides the form method.
  • formnovalidate: Turns off validation for a button.
  • novalidate: Turns off validation for the whole form.
  • enterkeyhint: Customises the Enter key text.
  • Validation: Checking user input for correctness.

๐Ÿง  Important Concepts

  • User experience matters. Advanced form techniques make forms faster and easier to use.
  • Mobile-first design. Use inputmode to optimise for mobile users.
  • Accessibility. Use autocomplete to help users with cognitive disabilities.
  • Flexibility. Use form attributes to design better layouts.

๐Ÿชœ Step-by-step Explanations

How to add a datalist to an input:

  1. Create a <datalist> with an id.
  2. Add <option> elements with value attributes.
  3. Add a list attribute to the input that matches the datalist id.

How to use inputmode:

  1. Add inputmode="numeric" for numbers.
  2. Add inputmode="email" for email addresses.
  3. Add inputmode="url" for URLs.

๐ŸŒ Real-life Examples

  • Example 1: Google's search box uses a datalist for suggestions.
  • Example 2: Amazon's checkout form uses autocomplete for addresses.
  • Example 3: Banking apps use inputmode to show number pads.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Example 1: A Nigerian bank website uses inputmode="numeric" for account numbers.
  • Example 2: A Nigerian e-commerce site uses autocomplete for shipping addresses.
  • Example 3: A Nigerian school portal uses datalist for state selection.

๐ŸŽฎ Fun Examples Children Can Relate To

  • Example 1: A game character creator with autocomplete for character names.
  • Example 2: A quiz app with datalist suggestions for answers.
  • Example 3: A story generator with inputmode for different input types.

๐Ÿ  Everyday Examples

  • Example 1: A shopping list with datalist suggestions.
  • Example 2: A contact form with autocomplete for name and email.
  • Example 3: A recipe form with inputmode for cooking time.

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง Parent Tips

  • Tip 1: Encourage your child to think about user experience when building forms.
  • Tip 2: Help them understand that mobile users need special attention.
  • Tip 3: Remind them that good forms make websites more accessible.

๐Ÿ’ก Interesting Facts

  • Fact 1: <datalist> was introduced in HTML5.
  • Fact 2: autocomplete is supported by all modern browsers.
  • Fact 3: inputmode was introduced in 2018.

๐Ÿค” Did You Know?

  • Did you know? That autocomplete can auto-fill passwords and credit card details?
  • Did you know? That inputmode works on both Android and iOS?
  • Did you know? That datalist works with any input type, not just text?

๐Ÿง  Remember This

  • 1. Use <datalist> for autocomplete suggestions.
  • 2. Use inputmode to control mobile keyboards.
  • 3. Use autocomplete for browser auto-fill.
  • 4. Use form attributes for flexible layouts.
  • 5. Use enterkeyhint to customise the Enter key.

โŒ Common Mistakes

  • Mistake 1: Forgetting to give the datalist an id.
  • Mistake 2: Not matching the list attribute with the datalist id.
  • Mistake 3: Using inputmode on desktop browsers โ€“ it is for mobile.
  • Mistake 4: Not using autocomplete โ€“ users appreciate it.
  • Mistake 5: Using novalidate without providing custom validation.

โœ… Best Practices

  • Practice 1: Always provide datalist suggestions for common inputs.
  • Practice 2: Use inputmode to optimise for mobile users.
  • Practice 3: Use autocomplete to save users time.
  • Practice 4: Use form attributes for flexible layouts.
  • Practice 5: Use enterkeyhint to improve mobile UX.

๐Ÿ“Š ASCII Illustrations

Datalist Flow

        User types in input
              |
              V
        Browser checks the datalist
              |
              V
        Suggestions appear below the input
              |
              V
        User clicks a suggestion โ†’ field is filled
    

inputmode on Mobile

        inputmode="numeric" โ†’ number pad
        inputmode="email" โ†’ email keyboard (with @ and .)
        inputmode="url" โ†’ URL keyboard (with .com and /)
    

Form Attributes

        <form id="myForm">
              |
              +--- formaction โ†’ different URL
              +--- formmethod โ†’ different method
              +--- formnovalidate โ†’ skip validation
              +--- formenctype โ†’ different encoding
        </form>
    

๐Ÿ“‹ Comparison Tables

inputmode Values

Value What it does Best used for
numeric Shows a number pad Phone numbers, PINs, quantities
email Shows an email keyboard Email addresses
url Shows a URL keyboard Website addresses
text Shows a regular keyboard General text
search Shows a search keyboard Search fields

Form Attributes for Buttons

Attribute What it does Example
formaction Overrides the form action formaction="/special"
formmethod Overrides the form method formmethod="POST"
formnovalidate Turns off validation formnovalidate
formenctype Overrides the encoding type formenctype="multipart/form-data"

๐Ÿ“š End-of-Module Summary

Excellent work, form wizard! ๐Ÿ“ You have completed Module 6 of HTML Level Three.

Let us recap what you have learned:

  • How to use <datalist> for autocomplete suggestions.
  • How to use inputmode to control the mobile keyboard.
  • How to use autocomplete for browser auto-fill.
  • How to use form attributes to link inputs outside the form.
  • How to use formaction, formmethod, and formnovalidate.
  • How to use novalidate to turn off all validation.
  • How to use enterkeyhint to customise the Enter key.

You now know how to build smart, user-friendly, and advanced forms that work great on any device. This is a professional skill used by top companies around the world!

โ“ Frequently Asked Questions

  • Q1: What is the difference between <datalist> and <select>?
    A: <datalist> is a text input with suggestions. <select> is a dropdown menu.
  • Q2: Does inputmode work on desktop browsers?
    A: No โ€“ it only works on mobile browsers.
  • Q3: What is autocomplete used for?
    A: It tells the browser to auto-fill fields with saved user data.
  • Q4: Can I use form attributes with any input type?
    A: Yes โ€“ they work with all input types.
  • Q5: What is the difference between novalidate and formnovalidate?
    A: novalidate turns off validation for the whole form. formnovalidate turns it off for a specific button.
  • Q6: What does enterkeyhint do?
    A: It customises the text on the Enter key on mobile keyboards.
  • Q7: Can I use datalist with input type="number"?
    A: Yes โ€“ but the suggestions must be numbers.
  • Q8: What is the default inputmode?
    A: The default is text.
  • Q9: Can I use autocomplete with passwords?
    A: Yes โ€“ use autocomplete="current-password" or new-password.
  • Q10: What are some common autocomplete values?
    A: name, email, tel, address, country.

๐Ÿ”— Matching Exercises

Match the term on the left with its correct description on the right.

Term Description
<datalist> A. Controls the mobile keyboard
inputmode B. Provides autocomplete suggestions
autocomplete C. Turns off validation for the whole form
form attribute D. Enables browser auto-fill
novalidate E. Links an input to a form outside it

(Answers: 1-B, 2-A, 3-D, 4-E, 5-C)

๐Ÿ“ Scenario-based Exercises

Scenario 1: You are building a registration form for a Nigerian school. You want to make it easy for parents to fill in their child's information. Add autocomplete suggestions for state names and use inputmode for phone numbers.

Question: Write the HTML code with <datalist>, inputmode, and autocomplete.

Scenario 2: You are building a contact form with two submit buttons โ€“ one to send the message and one to save as a draft. The draft button should skip validation.

Question: Write the HTML code with formnovalidate.

๐Ÿ‘ฅ Group Activity

Activity: In groups of 3โ€“4 students, build an advanced contact form. Each student is responsible for one part:

  • Student 1: Adds <datalist> suggestions for country/state.
  • Student 2: Adds inputmode for phone and email fields.
  • Student 3: Adds autocomplete for name, email, and phone.
  • Student 4: Adds a "Save Draft" button with formnovalidate.

Combine your work into a single form and present it to the class.

๐Ÿง‘โ€๐Ÿ’ป Individual Activity

Activity: Create a "Profile Update" form with the following fields:

  • Full Name (with autocomplete="name").
  • Email (with inputmode="email" and autocomplete="email").
  • Phone (with inputmode="numeric" and autocomplete="tel").
  • State (with a <datalist> of Nigerian states).
  • A "Save" button and a "Cancel" button (with formnovalidate).

Save it as profile.html and open it in your browser.

๐Ÿ› ๏ธ Mini Project

Project: Advanced Registration Form

Instructions: Build a registration form for a fictional Nigerian website. Your form should include:

  • โœ… Full Name (with autocomplete).
  • โœ… Email (with inputmode="email" and autocomplete).
  • โœ… Phone Number (with inputmode="numeric" and autocomplete).
  • โœ… State (with a <datalist> of Nigerian states).
  • โœ… City (with a <datalist> of Nigerian cities).
  • โœ… A "Submit" button and a "Save Draft" button (with formnovalidate).
  • โœ… enterkeyhint on all input fields.

Bonus: Add inputmode="search" to a search field.

๐Ÿ“‹ Practical Assignment

Assignment: Create a "Feedback Form" for a Nigerian restaurant. Your form should include:

  • Name (with autocomplete).
  • Email (with inputmode="email" and autocomplete).
  • Rating (with a <datalist> of numbers 1โ€“5).
  • Feedback (textarea).
  • A "Submit" button.
  • Use enterkeyhint on all inputs.

Submit your HTML file.

๐Ÿ”‘ Key Takeaways

  • 1. <datalist> provides autocomplete suggestions.
  • 2. inputmode controls mobile keyboards.
  • 3. autocomplete enables browser auto-fill.
  • 4. form attributes give you layout flexibility.
  • 5. formnovalidate and novalidate control validation.
  • 6. enterkeyhint improves mobile UX.

๐Ÿ’ฌ Classroom Discussion Questions

  • 1. Why do you think autocomplete is important for user experience?
  • 2. How would you explain inputmode to a 10-year-old?
  • 3. What are some ways to make forms more accessible?
  • 4. How can advanced form techniques help Nigerian businesses?
  • 5. When would you use formnovalidate instead of novalidate?

๐Ÿš€ Preparation for Module 7

Excellent work on Module 6! You have learned how to build advanced forms with smart features. In Module 7, we will dive into SVG โ€“ Scalable Vector Graphics. You will learn how to:

  • Draw shapes, lines, and text with SVG.
  • Add colours, gradients, and animations.
  • Use SVG for icons and logos.
  • Build a scalable logo and icon set.

Before you start Module 7, make sure you can:

  • Use <datalist> for autocomplete.
  • Use inputmode for mobile keyboards.
  • Use autocomplete for auto-fill.

Keep building and experimenting โ€“ you are on your way to becoming a professional web developer! ๐Ÿ’ป๐ŸŒŸ


Module 6: Advanced Forms & Inputs • Written with ๐Ÿ’– for young coders in Nigeria and around the world.

8

Module Seven

Module 7: SVG โ€“ Scalable Vector Graphics

๐Ÿ“ Module 7: SVG โ€“ Scalable Vector Graphics

Creating crisp, scalable graphics that never get blurry!

๐Ÿ“– Module Introduction

Welcome to Module 7 of your HTML Level Three journey! In Module 1, you learned about structured data. In Module 2, you learned about Canvas. In Module 3, you learned about Drag and Drop. In Module 4, you learned about Web Components. In Module 5, you learned about Templates and Slots. In Module 6, you learned about Advanced Forms.

Now, in Module 7, we are going to learn about SVG โ€“ Scalable Vector Graphics. SVG is a way to add graphics to your web pages that never get blurry, no matter how much you zoom in!

Have you ever seen a logo that looks crisp and clear on a phone, a tablet, and a big TV? That is probably an SVG! Unlike regular images (like JPG or PNG), SVG graphics are made of code, not pixels. This means they can scale to any size without losing quality.

In this module, you will learn:

  • What SVG is and why it is better than raster images.
  • How to draw shapes โ€“ rectangles, circles, lines, and paths.
  • How to add colours, gradients, and text.
  • How to use SVG for icons and logos.
  • How to animate SVG graphics.
  • How to build a scalable logo and icon set.

Think of this module as learning to draw with code. By the end, you will be able to create beautiful, crisp graphics that look perfect on any screen. Let us begin!

๐ŸŽฏ Learning Objectives

By the end of this module, you will be able to:

  • Explain what SVG is and why it is better than raster images.
  • Draw basic shapes โ€“ rectangles, circles, lines, and paths.
  • Add colours, gradients, and text to SVG graphics.
  • Use SVG for icons and logos.
  • Animate SVG with CSS.
  • Build a scalable logo and icon set.

๐Ÿ“š Warm-up Story: Tundeโ€™s Logo Design

Tunde was a 13-year-old boy who loved drawing. He had started a small business selling handmade crafts online. He needed a logo for his business, but every time he tried to use an image, it looked blurry on different screens.

Tundeโ€™s big sister, who was a web developer, said, โ€œTunde, you need to use SVG! It is a type of graphic that never gets blurry โ€“ it looks perfect on any screen, from a phone to a giant TV.โ€

Tunde learned how to use SVG. He drew a simple logo with a circle, a rectangle, and some text โ€“ all using code. He saved it as an SVG file and used it on his website. The logo looked crisp and clear on every device. His customers loved it!

In this module, you will learn exactly what Tunde learned. You will learn how to create beautiful, scalable graphics with SVG. Let us get started!

๐Ÿงฉ Main Lessons

Lesson 1: What is SVG?

Definition: SVG stands for Scalable Vector Graphics. It is a way to create graphics using code (XML) instead of pixels.

Why important: SVG graphics never get blurry โ€“ they look perfect on any screen size, from a small phone to a large monitor.

Simple explanation: SVG is like drawing with instructions โ€“ you tell the computer "draw a circle here, a line there," and it creates the graphic perfectly.

Real-life example: A blueprint for a building โ€“ it is a set of instructions that can be scaled to any size.

School example: A ruler โ€“ it measures accurately at any size. SVG is like a ruler for graphics.

Home example: A pattern for a dress โ€“ you can make it in any size and it still looks the same.

Nigerian example: A traditional Nigerian pattern โ€“ it can be woven in any size and still looks beautiful.

Comparison:

Feature Raster (JPG, PNG) SVG
Made of Pixels Code (vectors)
Scalability Gets blurry Never gets blurry
File size Large Small
Editing Hard Easy (text-based)
๐Ÿ“Œ Mini summary: SVG is a way to create graphics with code. They never get blurry and are perfect for logos and icons.

Lesson 2: The <svg> Element โ€“ The Container

Definition: The <svg> element is the container for all SVG graphics.

Why important: It is the canvas where you draw your SVG graphics.

Simple explanation: <svg> is like a blank piece of paper that you can draw on.

Code example:

        <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
            <!-- SVG shapes go here -->
        </svg>
    
๐Ÿ“Œ Mini summary: <svg> is the container for SVG graphics. Use width and height to set the size.

Lesson 3: Drawing Rectangles โ€“ <rect>

Definition: <rect> draws a rectangle.

Why important: Rectangles are one of the most basic shapes โ€“ they are used in logos, icons, and layouts.

Code example:

        <rect x="20" y="20" width="100" height="50" fill="blue" />
    
๐Ÿ“Œ Mini summary: <rect> draws a rectangle. Use x, y, width, height, and fill.

Lesson 4: Drawing Circles โ€“ <circle>

Definition: <circle> draws a circle.

Why important: Circles are used for buttons, icons, and many other graphics.

Code example:

        <circle cx="100" cy="100" r="50" fill="red" />
    
๐Ÿ“Œ Mini summary: <circle> draws a circle. Use cx, cy, r, and fill.

Lesson 5: Drawing Lines โ€“ <line>

Definition: <line> draws a line.

Why important: Lines are used for borders, dividers, and connecting shapes.

Code example:

        <line x1="10" y1="10" x2="150" y2="150" stroke="black" stroke-width="2" />
    
๐Ÿ“Œ Mini summary: <line> draws a line. Use x1, y1, x2, y2, stroke, and stroke-width.

Lesson 6: Drawing Ellipses โ€“ <ellipse>

Definition: <ellipse> draws an ellipse (an oval shape).

Why important: Ellipses are used for many types of graphics โ€“ like buttons, icons, and more.

Code example:

        <ellipse cx="100" cy="100" rx="80" ry="40" fill="green" />
    
๐Ÿ“Œ Mini summary: <ellipse> draws an ellipse. Use cx, cy, rx, ry, and fill.

Lesson 7: Drawing Polygons โ€“ <polygon>

Definition: <polygon> draws a closed shape with multiple sides (like a triangle or star).

Why important: Polygons are used for many types of graphics โ€“ like stars, arrows, and complex shapes.

Code example:

        <polygon points="50,10 100,80 0,80" fill="yellow" />
    
๐Ÿ“Œ Mini summary: <polygon> draws a multi-sided shape. Use points and fill.

Lesson 8: The <path> Element โ€“ Drawing Anything

Definition: <path> is the most powerful SVG element โ€“ it can draw anything using a series of commands.

Why important: Paths let you create complex shapes like curves, arcs, and custom designs.

Simple explanation: <path> is like a pen that you can move around to draw any shape.

Common path commands:

  • M โ€“ move to (x,y)
  • L โ€“ line to (x,y)
  • H โ€“ horizontal line to x
  • V โ€“ vertical line to y
  • C โ€“ cubic bezier curve
  • Q โ€“ quadratic bezier curve
  • Z โ€“ close path

Code example:

        <path d="M 10 10 L 100 10 L 100 100 L 10 100 Z" fill="purple" />
    
๐Ÿ“Œ Mini summary: <path> is the most powerful SVG element. Use commands like M, L, and Z to draw any shape.

Lesson 9: Adding Colours โ€“ fill and stroke

Definition: fill sets the inside colour. stroke sets the outline colour.

Why important: Colours make your graphics beautiful and vibrant.

Code example:

        <rect x="20" y="20" width="100" height="50" fill="blue" stroke="darkblue" stroke-width="3" />
    
๐Ÿ“Œ Mini summary: fill is the inside colour. stroke is the outline colour.

Lesson 10: Adding Text โ€“ <text>

Definition: <text> adds text to your SVG graphic.

Why important: You can add labels, titles, and information to your SVG graphics.

Code example:

        <text x="20" y="50" font-size="24" fill="black">Hello SVG!</text>
    
๐Ÿ“Œ Mini summary: <text> adds text to SVG. Use x, y, font-size, and fill.

Lesson 11: Gradients โ€“ Smooth Colour Transitions

Definition: Gradients create smooth transitions between two or more colours.

Why important: Gradients make your graphics look professional and smooth.

Code example:

        <defs>
            <linearGradient id="myGrad" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stop-color="red" />
                <stop offset="100%" stop-color="blue" />
            </linearGradient>
        </defs>
        <rect x="20" y="20" width="100" height="50" fill="url(#myGrad)" />
    
๐Ÿ“Œ Mini summary: Gradients create smooth colour transitions. Use <linearGradient> and stop elements.

Lesson 12: Using SVG for Icons

Definition: SVG is perfect for icons โ€“ they are small, scalable, and look great on any screen.

Why important: Icons are used everywhere โ€“ in menus, buttons, and navigation bars.

Simple explanation: SVG icons are like crisp, clean stamps that you can use anywhere.

Code example (a simple home icon):

        <svg width="24" height="24" viewBox="0 0 24 24">
            <path d="M12 3 L2 12 L5 12 L5 21 L9 21 L9 15 L15 15 L15 21 L19 21 L19 12 L22 12 L12 3 Z" fill="currentColor" />
        </svg>
    
๐Ÿ“Œ Mini summary: SVG is perfect for icons. They are small, scalable, and look great on any screen.

๐Ÿ“– Key Vocabulary

  • SVG: Scalable Vector Graphics โ€“ graphics made with code.
  • Vector: A graphic made of paths, not pixels.
  • Scalable: Can be resized without losing quality.
  • Raster: A graphic made of pixels (JPG, PNG).
  • Path: A sequence of drawing commands.
  • Fill: The inside colour of a shape.
  • Stroke: The outline colour of a shape.
  • Gradient: A smooth transition between colours.
  • viewBox: Defines the coordinate system.
  • defs: Defines reusable elements like gradients.

๐Ÿง  Important Concepts

  • SVG is code. You can write it by hand, just like HTML.
  • SVG never gets blurry. It scales perfectly to any size.
  • SVG is great for logos and icons. They look crisp on any screen.
  • SVG can be animated. You can use CSS to animate SVG elements.

๐Ÿชœ Step-by-step Explanations

How to create an SVG logo:

  1. Create an <svg> element with width and height.
  2. Add shapes โ€“ <rect>, <circle>, etc.
  3. Add text with <text>.
  4. Add colours with fill and stroke.
  5. Save as an SVG file or embed directly in HTML.

How to create an SVG icon:

  1. Create an <svg> with viewBox.
  2. Use <path> to draw the icon shape.
  3. Set fill="currentColor" to inherit the parent colour.

๐ŸŒ Real-life Examples

  • Example 1: Google uses SVG for its logo and icons.
  • Example 2: Twitter's bird logo is an SVG.
  • Example 3: Many modern websites use SVG for icons.

๐Ÿ‡ณ๐Ÿ‡ฌ Nigerian Examples

  • Example 1: A Nigerian company logo designed in SVG.
  • Example 2: SVG icons for a Nigerian e-commerce site.
  • Example 3: SVG graphics for a Nigerian school website.

๐ŸŽฎ Fun Examples Children Can Relate To

  • Example 1: A game character drawn with SVG.
  • Example 2: A star rating component with SVG stars.
  • Example 3: A weather icon set with SVG.

๐Ÿ  Everyday Examples

  • Example 1: A family logo or crest.
  • Example 2: Icons for a personal website.
  • Example 3: A custom map with SVG.

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง Parent Tips

  • Tip 1: Encourage your child to use SVG for their projects โ€“ it is a professional skill.
  • Tip 2: Help them understand that SVG is like drawing with code.
  • Tip 3: Remind them that SVG graphics never get blurry.

๐Ÿ’ก Interesting Facts

  • Fact 1: SVG was created in 1999.
  • Fact 2: SVG is supported by all modern browsers.
  • Fact 3: SVG files are usually smaller than JPG or PNG files.

๐Ÿค” Did You Know?

  • Did you know? That you can animate SVG with CSS?
  • Did you know? That SVG can be edited in any text editor?
  • Did you know? That SVG is used by many popular websites for their logos?

๐Ÿง  Remember This

  • 1. SVG stands for Scalable Vector Graphics.
  • 2. SVG never gets blurry โ€“ it scales perfectly.
  • 3. Use <svg> as the container.
  • 4. Use fill and stroke for colours.
  • 5. Use <path> for complex shapes.

โŒ Common Mistakes

  • Mistake 1: Forgetting the xmlns attribute.
  • Mistake 2: Using pixel values instead of percentages.
  • Mistake 3: Not using viewBox โ€“ it makes scaling easier.
  • Mistake 4: Forgetting to close tags.
  • Mistake 5: Using colours without # โ€“ e.g., #ff0000.

โœ… Best Practices

  • Practice 1: Always use viewBox for responsive SVG.
  • Practice 2: Use currentColor for icons to inherit colour.
  • Practice 3: Keep SVG code clean and well-formatted.
  • Practice 4: Use <defs> for reusable elements.
  • Practice 5: Test SVG on different screen sizes.

๐Ÿ“Š ASCII Illustrations

SVG Shapes

        Rectangle: <rect x="20" y="20" width="100" height="50" />
        Circle:    <circle cx="100" cy="100" r="50" />
        Line:      <line x1="10" y1="10" x2="150" y2="150" />
        Polygon:   <polygon points="50,10 100,80 0,80" />
        Path:      <path d="M 10 10 L 100 10 L 100 100 Z" />
    

SVG Structure

        <svg>
        +----------------------------------+
        |  <defs>                         |
        |    <linearGradient id="grad" /> |
        |  </defs>                        |
        |  <rect />                       |
        |  <circle />                     |
        |  <text />                       |
        +----------------------------------+
        </svg>
    

Path Commands

        M โ†’ Move to
        L โ†’ Line to
        H โ†’ Horizontal line
        V โ†’ Vertical line
        C โ†’ Cubic bezier
        Q โ†’ Quadratic bezier
        Z โ†’ Close path
    

๐Ÿ“‹ Comparison Tables

SVG vs Canvas

Feature SVG Canvas
Type Vector Pixel (raster)
Scalability Never gets blurry Gets blurry
Editing Easy (code) Hard (pixels)
Best for Logos, icons, graphics Games, animations, data vis

SVG Elements

Element What it does Example
<rect> Draws a rectangle rect x="10" y="10" width="50" height="30"
<circle> Draws a circle circle cx="50" cy="50" r="25"
<line> Draws a line line x1="10" y1="10" x2="90" y2="90"
<polygon> Draws a multi-sided shape polygon points="50,10 100,80 0,80"
<path> Draws any shape path d="M 10 10 L 90 90 Z"
<text> Adds text text x="20" y="50" font-size="20"

๐Ÿ“š End-of-Module Summary

Fantastic work, SVG artist! ๐Ÿ“ You have completed Module 7 of HTML Level Three.

Let us recap what you have learned:

  • What SVG is and why it is better than raster images.
  • How to draw shapes โ€“ rectangles, circles, lines, and paths.
  • How to add colours, gradients, and text.
  • How to use SVG for icons and logos.
  • How to use the viewBox for responsive SVG.
  • How to use <defs> for reusable elements.

You now know how to create beautiful, scalable graphics that look perfect on any screen. This is a professional skill used by designers and developers around the world!

โ“ Frequently Asked Questions

  • Q1: What is the difference between SVG and Canvas?
    A: SVG is vector-based (never gets blurry). Canvas is pixel-based (gets blurry). SVG is better for logos and icons.
  • Q2: Can I animate SVG?
    A: Yes โ€“ you can animate SVG with CSS or JavaScript.
  • Q3: Is SVG supported in all browsers?
    A: Yes โ€“ all modern browsers support SVG.
  • Q4: What is viewBox?
    A: viewBox defines the coordinate system for the SVG.
  • Q5: Can I use SVG in HTML?
    A: Yes โ€“ you can embed SVG directly in HTML.
  • Q6: What is fill?
    A: fill sets the inside colour of a shape.
  • Q7: What is stroke?
    A: stroke sets the outline colour of a shape.
  • Q8: What is a path in SVG?
    A: A path is a sequence of drawing commands like M, L, and Z.
  • Q9: Can I reuse SVG elements?
    A: Yes โ€“ use <defs> to define reusable elements.
  • Q10: What is the xmlns attribute?
    A: It defines the XML namespace for SVG.

๐Ÿ”— Matching Exercises

Match the SVG element on the left with its correct description on the right.

Element Description
<rect> A. Draws a circle
<circle> B. Draws a rectangle
<line> C. Draws any shape
<path> D. Draws a line
<text> E. Adds text
<polygon> F. Draws a multi-sided shape

(Answers: 1-B, 2-A, 3-D, 4-C, 5-E, 6-F)

๐Ÿ“ Scenario-based Exercises

Scenario 1: You are building a website for a Nigerian company called "Lagos Tech". You need a simple logo with the text "Lagos Tech" and a circle.

Question: Write the SVG code for this logo.

Scenario 2: You are building a weather app and need icons for "Sunny", "Cloudy", and "Rainy".

Question: Write the SVG code for a sunny icon (a circle with rays).

๐Ÿ‘ฅ Group Activity

Activity: In groups of 3โ€“4 students, create an SVG icon set. Each student designs one icon:

  • Student 1: Home icon.
  • Student 2: Search icon.
  • Student 3: User icon.
  • Student 4: Settings icon.

Each icon should be a clean SVG path. Combine them into a single page and present to the class.

๐Ÿง‘โ€๐Ÿ’ป Individual Activity

Activity: Create an SVG logo for yourself. It should include:

  • Your initials or name.
  • At least two different shapes (e.g., circle + rectangle).
  • At least two colours.
  • Text with your name.

Save it as logo.svg and open it in your browser.

๐Ÿ› ๏ธ Mini Project

Project: SVG Icon Library

Instructions: Build an SVG icon library with at least 5 icons:

  • โœ… Home icon
  • โœ… Search icon
  • โœ… User icon
  • โœ… Settings icon
  • โœ… Star icon

Requirements:

  • โœ… Each icon should be in its own <svg> element.
  • โœ… Use viewBox for scalability.
  • โœ… Use currentColor for the fill.
  • โœ… Display all icons in a grid on a single page.

Bonus: Add a <defs> section with reusable gradients.

๐Ÿ“‹ Practical Assignment

Assignment: Create a page that displays a Nigerian flag using SVG. The flag should have:

  • Three vertical stripes: green, white, green.
  • The green stripes should be equal size.
  • The white stripe should be in the middle.
  • Use the exact colours of the Nigerian flag.

Submit your HTML file.

๐Ÿ”‘ Key Takeaways

  • 1. SVG stands for Scalable Vector Graphics.
  • 2. SVG never gets blurry โ€“ it scales perfectly.
  • 3. Use <svg> as the container.
  • 4. Use fill and stroke for colours.
  • 5. Use <path> for complex shapes.
  • 6. Use viewBox for responsive SVG.
  • 7. SVG is perfect for logos and icons.

๐Ÿ’ฌ Classroom Discussion Questions

  • 1. Why do you think SVG is better than JPG for logos?
  • 2. How would you explain the difference between SVG and Canvas?
  • 3. What are some ways SVG can be used on a website?
  • 4. How can SVG help Nigerian businesses?
  • 5. What is the importance of viewBox in SVG?

๐Ÿš€ Preparation for Module 8

Excellent work on Module 7! You have learned how to create beautiful, scalable graphics with SVG. In Module 8, the final module of Level Three, we will dive into Performance & Advanced Accessibility. You will learn how to:

  • Optimise your website for speed and performance.
  • Use advanced accessibility techniques.
  • Score 100 on Lighthouse.
  • Make your website lightning-fast and truly inclusive.

Before you start Module 8, make sure you can:

  • Create basic SVG shapes.
  • Use fill and stroke.
  • Use viewBox for responsive SVG.

Keep building and experimenting โ€“ you are on your way to becoming a professional web developer! ๐Ÿ’ป๐ŸŒŸ


Module 7: SVG โ€“ Scalable Vector Graphics • Written with ๐Ÿ’– for young coders in Nigeria and around the world.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, pass the exam, and unlock Practice Tools plus a verified certificate with your name on it โ€” โ‚ฆ4,000/month.

๐ŸŽ“ Sign Up & Unlock for โ‚ฆ4,000/month
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - try them free for 7 days, no card required.
โ†’