Take your HTML skills to the professional level. Learn structured data, Canvas, Web Components, SVG, and advanced accessibility.
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.
Before starting Level Three, you should be comfortable with everything taught in Level One and Level Two. Specifically, you should know:
<header>, <nav>, <main>, <article>, <aside>, <footer>.<figure>, <details>, <summary>, <em>, <strong>, <blockquote>, <cite>.target="_blank", mailto:, tel:.<picture>, srcset, loading="lazy", <video>, <audio>, <iframe>.<label>, <fieldset>, input types (email, tel, number, date), <select>, <textarea>, required, pattern.<thead>, <tbody>, <tfoot>, colspan, rowspan, scope.lang attribute.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 |
Objective: Learn how to use Schema.org vocabulary to add structured data to your HTML, helping search engines understand your content better.
itemscope, itemtype, itemprop.Objective: Learn how to use the <canvas> element to draw graphics, shapes, and animations.
Objective: Learn how to make elements draggable and droppable for interactive user interfaces.
draggable.dragstart, dragend.dragover, drop.Objective: Learn how to create your own custom HTML tags using Web Components.
class and customElements.define().<fancy-card> custom element that can be reused across a website.
Objective: Learn how to reuse HTML code efficiently with <template> and <slot>.
<template> โ writing HTML that is not displayed until used.<template> with JavaScript to clone content.<slot> โ creating placeholders inside components.<template> to generate image cards dynamically.
Objective: Learn advanced form techniques to build smarter, more user-friendly forms.
<datalist> for autocomplete suggestions.inputmode to control mobile keyboards.autocomplete to help browsers auto-fill forms.form attributes to link inputs outside the <form>.novalidate to turn off browser validation.Objective: Learn how to use SVG to add crisp, scalable graphics to your web pages.
Objective: Learn how to make your websites lightning-fast and truly inclusive for everyone.
Project Brief: Build a professional portfolio website that showcases everything you have learned in Level Three. Your website must include:
<project-card>).<template> to generate dynamic content.Submission: Submit your HTML files, along with a short report on how you implemented each feature.
<template> and <slot> help you reuse HTML code efficiently.<datalist> and autocomplete make forms smarter.Helping search engines understand your content like never before!
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:
itemscope, itemtype, and itemprop.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!
By the end of this module, you will be able to:
itemscope, itemtype, and itemprop.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!
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!"
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!
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:
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.itemscope, itemtype, itemprop)
to add structured data to your pages.
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>
itemscope creates a new
item. All content inside is part of that item.
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>
itemtype tells search
engines what type of thing this is. Use a Schema.org URL.
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>
itemprop adds details
(properties) to your item. It tells search engines specific information
about the item.
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>
Person to mark up
information about a person โ like their name, job, and location.
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>
Organization to mark
up information about a company, school, or group.
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>
Product to mark up
information about items for sale โ like name, description, and price.
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>
Recipe to mark up
recipes โ with ingredients, cooking time, and ratings.
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>
Event to mark up
events โ like concerts, conferences, and festivals.
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>
Review to mark up
reviews โ with ratings and comments.
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:
https://schema.org/Recipe.itemscope and itemtype to the container.itemprop for the name, description, and cooking time.itemprop="recipeIngredient" for each ingredient.AggregateRating.Recipe to mark up Egusi soup, Suya, and Jollof rice recipes.Product to mark up items like phone cases, clothes, and shoes.Event to mark up concerts, festivals, and cultural events.Product to mark up game titles, prices, and ratings.Article to mark up a news article about a school event.Movie to mark up movie titles, directors, and release dates.Recipe to mark up family recipes.ImageObject to mark up photos.Event to mark up birthdays and holidays.itemscope, itemtype, itemprop.itemscope or itemtype attributes.itemtype URL โ always use https://schema.org/....itemprop on the right elements โ it must be on the element that contains the property value.Recipe instead of Thing.
+------------------------------------------+
| <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"
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! ๐
Normal result:
----------------------------------------
Jollof Rice Recipe | My Blog
----------------------------------------
Rich result:
----------------------------------------
โญโญโญโญ (4.5) Jollof Rice Recipe
โฑ 30 mins | ๐ Rice, Tomatoes, Onions
[Picture of Jollof Rice]
----------------------------------------
| 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. |
| 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 |
Amazing work, structured data master! ๐ You have completed Module 1 of HTML Level Three.
Let us recap what you have learned:
itemscope, itemtype, and itemprop.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!
<script> tag.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 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.
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.
Activity: Create a page about your favourite Nigerian food. Include:
Recipe type with name, description, cooking time, and ingredients.AggregateRating with a rating value.Save it as recipe.html and submit it.
Instructions: Create a page about yourself and your interests. Your page must include structured data for:
Person โ your name, job title, and location.Organization โ your school or a club you belong to.Product โ a product you like or use.Recipe โ your favourite Nigerian recipe.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.
Assignment: Create a page for a Nigerian restaurant called โTasty Bitesโ. Include:
Organization type with the restaurant name, address, and phone number.Product type for the โJollof Riceโ dish with price and description.AggregateRating with a rating value.Menu type (you can research this on Schema.org).itemscope, itemtype, and itemprop.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:
<canvas> element to draw graphics.Before you start Module 2, make sure you can:
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.
Drawing graphics, shapes, and animations right in your browser!
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:
<canvas> element is and how to use it.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!
By the end of this module, you will be able to:
<canvas> element in HTML.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!
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
<canvas> element is the paper,
and JavaScript is the paintbrush.
<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>
<canvas> is the
container for your drawings. Give it an id so you can
access it with JavaScript.
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>
getContext('2d')
method gives you the drawing context. You need it to draw on the canvas.
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>
fillRect() draws a
filled rectangle. strokeRect() draws only the outline.
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>
arc() draws circles
and arcs. Use beginPath() and stroke() or
fill() to complete the drawing.
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>
moveTo() and
lineTo() let you draw lines. Use closePath()
to close a shape.
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;
fillStyle sets the
fill colour. strokeStyle sets the outline colour.
lineWidth sets the outline thickness.
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);
createLinearGradient() or
createRadialGradient().
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);
fillText() draws
filled text. strokeText() draws outlined text. Use
font to set the text style.
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);
};
drawImage() adds
images to your canvas. Make sure the image loads before drawing.
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);
clearRect() erases
the canvas. Use it to prepare for new drawings or 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();
requestAnimationFrame() for smooth animation.
requestAnimationFrame() for smooth animations. It is better than setInterval().beginPath() to start a new path.arc(x, y, radius, startAngle, endAngle).fillStyle and strokeStyle.fill() and stroke().draw() function.clearRect().requestAnimationFrame(draw) to repeat.getContext('2d') to draw.fillRect() for filled shapes and strokeRect() for outlines.arc() for circles and moveTo()/lineTo() for lines.requestAnimationFrame() for smooth animations.beginPath() before drawing a new shape.closePath() to close paths.setInterval() instead of requestAnimationFrame() โ it is less smooth.beginPath() before drawing each shape.requestAnimationFrame() for animations.save() and restore().
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!
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! ๐
(0,0) ---------- (400,0)
| |
| Canvas |
| |
(0,300) -------- (400,300)
| 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) |
| 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' |
Brilliant work, canvas artist! ๐จ You have completed Module 2 of HTML Level Three.
Let us recap what you have learned:
<canvas> element.getContext('2d').fillRect() and strokeRect().arc().moveTo() and lineTo().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!
clearRect(0, 0, canvas.width, canvas.height).canvas.toDataURL() to get an image.requestAnimationFrame()?mousemove and mousedown.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 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().
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.
<canvas> with a fixed size.input type="color").Present your drawing app to the class.
Activity: Create a page with a canvas that draws a smiley face. Your smiley face should include:
Save it as smiley.html and open it in your browser.
Instructions: Build a complete drawing app with the following features:
Bonus: Add a save button that lets users download their drawing as an image.
Assignment: Create a page with a canvas that draws a house. Your house should include:
Use colours to make it look nice. Submit your HTML file.
getContext('2d') to start drawing.fillRect(), arc(), and lineTo() for shapes.fillStyle, strokeStyle, and lineWidth for styles.requestAnimationFrame() for smooth animations.requestAnimationFrame() better than setInterval() for animations?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:
draggable attribute.dragstart, dragend.dragover, drop.Before you start Module 3, make sure you can:
<canvas> element and draw basic shapes.fillStyle and strokeStyle.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.
Building interactive interfaces by dragging and dropping!
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:
draggable attribute.dragstart, dragend, drag.dragover, drop, dragenter, dragleave.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!
By the end of this module, you will be able to:
draggable attribute.dragstart, dragend, drag.dragover, drop, dragenter, dragleave.dataTransfer object to pass data.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!
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"
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>
draggable="true"
makes an element draggable. This is the first step in drag and drop.
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>
dragstart fires
when dragging starts. dragend fires when it ends.
drag fires repeatedly while dragging.
dragover, drop, dragenter, dragleaveDefinition: 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>
dragover fires when
dragging over a drop zone. drop fires when the item is
dropped. Always prevent default on dragover to allow drops.
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);
});
dataTransfer stores
data during a drag. Use setData() on drag start and
getData() on drop.
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>
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';
});
dragenter and
dragleave to provide visual feedback โ like highlighting
the drop zone.
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);
}
});
e.dataTransfer.files
to access files dropped from the computer. This is great for file uploads.
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:
<li>.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';
});
effectAllowed sets
the allowed operation. dropEffect sets the visual feedback
for the drop.
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.draggable="true" to the element you want to drag.dragstart event listener to store data in dataTransfer.dragover (prevent default).drop on the drop zone to receive the data.dragover and prevent default.drop and access e.dataTransfer.files.dataTransfer object can store multiple types of data.dataTransfer can store files, text, and URLs?setDragImage()?draggable="true" to make elements draggable.dragover to allow drops.dataTransfer to pass data between drag and drop.dragenter and dragleave for visual feedback.draggable="true" โ the element will not be draggable.dragover โ the drop will not work.dataTransfer โ you will not be able to pass data.dragenter and dragleave โ no visual feedback.dataTransfer to pass all necessary data.
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 ๐
On the draggable element:
dragstart โ drag โ dragend
On the drop target:
dragenter โ dragover โ (dragleave if you leave) โ drop
dragstart: setData('text', 'value')
|
V
(drag operation happens)
|
V
drop: getData('text') โ receives 'value'
| 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 |
| 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' |
Fantastic work, drag-and-drop master! ๐ฑ๏ธ You have completed Module 3 of HTML Level Three.
Let us recap what you have learned:
draggable="true".dragstart, dragend, drag.dragover, drop, dragenter, dragleave.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!
dragover. Always use e.preventDefault().dataTransfer object?effectAllowed and dropEffect?effectAllowed sets the allowed operation. dropEffect sets the visual feedback.e.preventDefault() on dragstart to cancel it.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 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.
Activity: In groups of 3โ4 students, build a drag-and-drop colour sorter. You should have:
Present your colour sorter to the class.
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).
Save it as food-list.html and open it in your browser.
Instructions: Build a complete task manager with drag-and-drop features:
Bonus: Add local storage so tasks are saved when the page is refreshed.
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").
Submit your HTML file.
draggable="true" to make elements draggable.dragover to allow drops.dataTransfer to pass data between drag and drop.dataTransfer to a 10-year-old?dragover?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:
<my-header>.Before you start Module 4, make sure you can:
draggable="true".dataTransfer to pass data.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.
Creating your own custom HTML tags โ just like a professional!
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:
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!
By the end of this module, you will be able to:
customElements API.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!
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! ๐
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 |
+----------------------------------+
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);
customElements.define() to
register a new element.
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)
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);
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>
<slot> is a
placeholder for content from the outside. It lets you customise your
components.
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>
getAttribute() to read them.
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);
connectedCallback()
fires when a custom element is added to the page. Use it for
initialisation.
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);
<template> to separate structure
from logic.
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.HTMLElement.constructor(), set up the element.this.attachShadow({ mode: 'open' }) to create a Shadow DOM.customElements.define() to register the element.<template> in HTML.document.getElementById().template.content.cloneNode(true).<game-card> component for displaying video game characters.<quiz-question> component for a trivia game.<friend-profile> component for a social network.<family-member> component for a family tree.<recipe-card> component for a recipe book.<event-card> component for a calendar.customElements API was introduced in 2018.<slot> with multiple names for different content?<slot> to allow custom content.connectedCallback() for initialisation.this incorrectly inside the component.super() in the constructor.
+------------------------------------------+
| Custom Element |
| +----------------------------------+ |
| | Shadow DOM | |
| | +----------------------------+ | |
| | | Template | | |
| | | | | |
| | | | | |
| | | | | |
| | +----------------------------+ | |
| | +----------------------------+ | |
| | | Styles (encapsulated) | | |
| | | .card { ... } | | |
| | +----------------------------+ | |
| +----------------------------------+ |
+------------------------------------------+
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()
<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>
| 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) |
| 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 |
Brilliant work, component builder! ๐งฉ You have completed Module 4 of HTML Level Three.
Let us recap what you have learned:
connectedCallback().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!
slot?connectedCallback()?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 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.
Activity: In groups of 3โ4 students, build a component library together. Each student builds one component:
<my-header> โ a header with a title and navigation.<my-footer> โ a footer with copyright information.<fancy-card> โ a card with a title, image, and description.<custom-button> โ a button with a label and a click event.Combine your components into a single page and present it to the class.
Activity: Create a custom <user-profile> component. It should display:
Save it as profile.html and open it in your browser.
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.
Assignment: Create a page that uses at least 3 custom components. Your page should include:
<my-header> component for the header.<my-card> component for displaying information.<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.
customElements.define() to register a custom element.<slot> to allow custom content.connectedCallback() for initialisation.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:
<template> to define reusable HTML structures.<slot> to create placeholders for content.Before you start Module 5, make sure you can:
customElements.define().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.
Reusing HTML code like a pro โ with templates and slots!
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:
<template> element is and how to use it.<slot> element is and how to use it.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!
By the end of this module, you will be able to:
<template> is and why it is useful.<template> to define reusable HTML structures.<slot> is and why it is useful.<slot> to create placeholders for content.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!
<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 -->
<template>
defines reusable HTML structures. The content is not displayed until
you use it with JavaScript.
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! ๐
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>
template.content.cloneNode(true)
to clone a template. Then append the clone to the page.
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
template.content gives
you the HTML inside the template. Use it to clone the template.
<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>
<slot> is a
placeholder for content. It makes templates flexible and reusable.
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>
name
attribute. They let you put different content into different 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>
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>
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:
<template> for a photo card with slots for image and caption.<template> with an id.document.getElementById().template.content.cloneNode(true).<slot name="name">.slot="name".<template> element was introduced in HTML5.cloneNode(true) to copy a template.cloneNode(true) โ you need a deep clone.id โ you cannot find it.template.innerHTML instead of template.content.id.cloneNode(true) for deep cloning.
<template id="card">
+----------------------------------+
| <div class="card"> |
| <slot name="title">Title</slot>|
| <slot name="content">Content</slot>|
| </div> |
+----------------------------------+
</template>
Template (invisible)
|
V
JavaScript clones the template
|
V
Clone is appended to the page |
V
Content appears on the page! ๐
<my-card>
+----------------------------------+
| <span slot="title">My Title</span>|
| <p slot="content">My Content</p> |
+----------------------------------+
</my-card>
The slots get filled with the provided content.
| 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 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 |
Fantastic work, template master! ๐ You have completed Module 5 of HTML Level Three.
Let us recap what you have learned:
<template> element is and how to use it.<slot> element is and how to use it.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!
name attribute that lets you put different content in different slots.content property?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 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.
Activity: In groups of 3โ4 students, build a template-based gallery together. Each student contributes:
Present your gallery to the class.
Activity: Create a page with a template for a "friend profile" card. Each card should show:
Use JavaScript to create at least 3 friend profiles using the template. Save it as friends.html and open it in your browser.
Instructions: Build a recipe gallery using templates. Your gallery should include:
Bonus: Add a "search" feature that filters recipes by title.
Assignment: Create a page that displays a list of Nigerian cities using a template. Each city card should show:
Use a template with slots for each piece of data. Use JavaScript to create at least 5 city cards. Submit your HTML file.
cloneNode(true) to clone a template.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:
<datalist> for autocomplete suggestions.inputmode to control mobile keyboards.autocomplete for form auto-fill.form attributes to link inputs outside the form.novalidate to turn off validation.Before you start Module 6, make sure you can:
<template>.cloneNode(true).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.
Building smarter, more user-friendly forms with advanced techniques!
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:
<datalist> for autocomplete suggestions.inputmode to control the keyboard on mobile devices.autocomplete to help browsers auto-fill forms.form attributes to link inputs outside the <form> tag.novalidate to turn off browser validation.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!
By the end of this module, you will be able to:
<datalist> to provide autocomplete suggestions.inputmode to control mobile keyboards.autocomplete for form auto-fill.form attributes to link inputs outside the form.novalidate to turn off validation.enterkeyhint to customise the Enter key.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!
<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>
<datalist>
provides autocomplete suggestions. It makes typing faster and easier.
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>
list attribute
connects an input to a datalist. The id of the datalist
must match the list value.
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" />
inputmode controls
the keyboard that appears on mobile devices. Use numeric,
email, or url for the right keyboard.
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 namegiven-name โ first namefamily-name โ last nameemail โ email addresstel โ phone numberaddress โ full addresscountry โ countrypostal-code โ zip codeoff โ turn off autocompleteCode 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" />
autocomplete tells
the browser to auto-fill fields. Use values like name,
email, and tel.
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" />
form attribute
links an input to a form, even if the input is outside the form.
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>
formaction lets you
override the form's action for a specific button.
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>
formenctype overrides
the form's encoding type for a specific button โ useful for file uploads.
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>
formmethod overrides
the form's method (GET or POST) for a specific button.
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>
formnovalidate turns
off validation for a specific button โ useful for draft submissions.
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>
novalidate turns off
all validation for the whole form โ you can use your own validation.
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 โ defaultdone โ donego โ gonext โ nextprevious โ previoussearch โ searchsend โ sendCode example:
<input type="text" enterkeyhint="search" placeholder="Type to search..." />
<input type="text" enterkeyhint="send" placeholder="Type your message..." />
enterkeyhint customises
the text on the Enter key on mobile keyboards.
inputmode to optimise for mobile users.autocomplete to help users with cognitive disabilities.form attributes to design better layouts.<datalist> with an id.<option> elements with value attributes.list attribute to the input that matches the datalist id.inputmode="numeric" for numbers.inputmode="email" for email addresses.inputmode="url" for URLs.inputmode="numeric" for account numbers.autocomplete for shipping addresses.datalist for state selection.<datalist> was introduced in HTML5.autocomplete is supported by all modern browsers.inputmode was introduced in 2018.autocomplete can auto-fill passwords and credit card details?inputmode works on both Android and iOS?datalist works with any input type, not just text?<datalist> for autocomplete suggestions.inputmode to control mobile keyboards.autocomplete for browser auto-fill.form attributes for flexible layouts.enterkeyhint to customise the Enter key.id.list attribute with the datalist id.inputmode on desktop browsers โ it is for mobile.autocomplete โ users appreciate it.novalidate without providing custom validation.inputmode to optimise for mobile users.autocomplete to save users time.form attributes for flexible layouts.enterkeyhint to improve mobile UX.
User types in input
|
V
Browser checks the datalist
|
V
Suggestions appear below the input
|
V
User clicks a suggestion โ field is filled
inputmode="numeric" โ number pad
inputmode="email" โ email keyboard (with @ and .)
inputmode="url" โ URL keyboard (with .com and /)
<form id="myForm">
|
+--- formaction โ different URL
+--- formmethod โ different method
+--- formnovalidate โ skip validation
+--- formenctype โ different encoding
</form>
| 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 |
| 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" |
Excellent work, form wizard! ๐ You have completed Module 6 of HTML Level Three.
Let us recap what you have learned:
<datalist> for autocomplete suggestions.inputmode to control the mobile keyboard.autocomplete for browser auto-fill.form attributes to link inputs outside the form.formaction, formmethod, and formnovalidate.novalidate to turn off all validation.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!
<datalist> and <select>?<datalist> is a text input with suggestions. <select> is a dropdown menu.inputmode work on desktop browsers?autocomplete used for?form attributes with any input type?novalidate and formnovalidate?novalidate turns off validation for the whole form. formnovalidate turns it off for a specific button.enterkeyhint do?datalist with input type="number"?inputmode?text.autocomplete with passwords?autocomplete="current-password" or new-password.autocomplete values?name, email, tel, address, country.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 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.
Activity: In groups of 3โ4 students, build an advanced contact form. Each student is responsible for one part:
<datalist> suggestions for country/state.inputmode for phone and email fields.autocomplete for name, email, and phone.formnovalidate.Combine your work into a single form and present it to the class.
Activity: Create a "Profile Update" form with the following fields:
autocomplete="name").inputmode="email" and autocomplete="email").inputmode="numeric" and autocomplete="tel").<datalist> of Nigerian states).formnovalidate).Save it as profile.html and open it in your browser.
Instructions: Build a registration form for a fictional Nigerian website. Your form should include:
autocomplete).inputmode="email" and autocomplete).inputmode="numeric" and autocomplete).<datalist> of Nigerian states).<datalist> of Nigerian cities).formnovalidate).enterkeyhint on all input fields.Bonus: Add inputmode="search" to a search field.
Assignment: Create a "Feedback Form" for a Nigerian restaurant. Your form should include:
autocomplete).inputmode="email" and autocomplete).<datalist> of numbers 1โ5).enterkeyhint on all inputs.Submit your HTML file.
<datalist> provides autocomplete suggestions.inputmode controls mobile keyboards.autocomplete enables browser auto-fill.form attributes give you layout flexibility.formnovalidate and novalidate control validation.enterkeyhint improves mobile UX.inputmode to a 10-year-old?formnovalidate instead of novalidate?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:
Before you start Module 7, make sure you can:
<datalist> for autocomplete.inputmode for mobile keyboards.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.
Creating crisp, scalable graphics that never get blurry!
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:
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!
By the end of this module, you will be able to:
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!
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) |
<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>
<svg> is the
container for SVG graphics. Use width and height
to set the size.
<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" />
<rect> draws a
rectangle. Use x, y, width,
height, and fill.
<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" />
<circle> draws a
circle. Use cx, cy, r, and
fill.
<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" />
<line> draws a
line. Use x1, y1, x2,
y2, stroke, and stroke-width.
<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" />
<ellipse> draws
an ellipse. Use cx, cy, rx,
ry, and fill.
<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" />
<polygon> draws
a multi-sided shape. Use points and fill.
<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 xV โ vertical line to yC โ cubic bezier curveQ โ quadratic bezier curveZ โ close pathCode example:
<path d="M 10 10 L 100 10 L 100 100 L 10 100 Z" fill="purple" />
<path> is the
most powerful SVG element. Use commands like M, L,
and Z to draw any shape.
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" />
fill is the inside
colour. stroke is the outline colour.
<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>
<text> adds text
to SVG. Use x, y, font-size,
and fill.
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)" />
<linearGradient> and
stop elements.
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>
<svg> element with width and height.<rect>, <circle>, etc.<text>.fill and stroke.<svg> with viewBox.<path> to draw the icon shape.fill="currentColor" to inherit the parent colour.<svg> as the container.fill and stroke for colours.<path> for complex shapes.xmlns attribute.viewBox โ it makes scaling easier.# โ e.g., #ff0000.viewBox for responsive SVG.currentColor for icons to inherit colour.<defs> for reusable elements.
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>
+----------------------------------+
| <defs> |
| <linearGradient id="grad" /> |
| </defs> |
| <rect /> |
| <circle /> |
| <text /> |
+----------------------------------+
</svg>
M โ Move to
L โ Line to
H โ Horizontal line
V โ Vertical line
C โ Cubic bezier
Q โ Quadratic bezier
Z โ Close path
| 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 |
| 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" |
Fantastic work, SVG artist! ๐ You have completed Module 7 of HTML Level Three.
Let us recap what you have learned:
<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!
viewBox?viewBox defines the coordinate system for the SVG.fill?fill sets the inside colour of a shape.stroke?stroke sets the outline colour of a shape.M, L, and Z.<defs> to define reusable elements.xmlns attribute?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 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).
Activity: In groups of 3โ4 students, create an SVG icon set. Each student designs one icon:
Each icon should be a clean SVG path. Combine them into a single page and present to the class.
Activity: Create an SVG logo for yourself. It should include:
Save it as logo.svg and open it in your browser.
Instructions: Build an SVG icon library with at least 5 icons:
Requirements:
<svg> element.viewBox for scalability.currentColor for the fill.Bonus: Add a <defs> section with reusable gradients.
Assignment: Create a page that displays a Nigerian flag using SVG. The flag should have:
Submit your HTML file.
<svg> as the container.fill and stroke for colours.<path> for complex shapes.viewBox for responsive SVG.viewBox in SVG?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:
Before you start Module 8, make sure you can:
fill and stroke.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.