jQuery Exercises
Time to practise. Each task has a starter playground with the HTML ready and a // TODO where your jQuery goes. Edit the code, press ▶ Run, and test it in the preview. When you are done — or stuck — open the solution.
| # | Topic | Skills |
|---|---|---|
| 1 | Selectors | $(), .css(), positional methods |
| 2 | Events | .on(), $(this), .text() |
| 3 | Effects | .slideToggle(), callbacks |
| 4 | Get/Set | .val(), .text(), .attr() |
| 5 | Add/Remove | .append(), .remove(), delegation |
| 6 | Classes | .toggleClass(), .siblings() |
| 7 | Traversing | .closest(), .find(), .each() |
| 8 | Filtering | .filter(), .show()/.hide() |
| 9 | AJAX | $.getJSON(), building HTML |
| 10 | Plugin | $.fn, this.each, chaining |
Exercise 1 — Zebra list
Make every odd list item (index 1, 3, 5…) have a light grey background, make the first item bold, and log how many items there are.
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif">
<ul id="planets">
<li>Mercury</li><li>Venus</li><li>Earth</li><li>Mars</li><li>Jupiter</li><li>Saturn</li>
</ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// TODO: style odd items, bold the first one, log the count
</script>
</body>
</html>Show solution
const $items = $("#planets li");
$items.odd().css("background", "#eee");
$items.first().css("font-weight", "bold");
console.log("items:", $items.length); // 6Exercise 2 — Click counter buttons
Each button should show how many times it has been clicked, e.g. Like (3). Use one handler for all buttons.
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif">
<button class="count" data-label="Like">Like (0)</button>
<button class="count" data-label="Share">Share (0)</button>
<button class="count" data-label="Save">Save (0)</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// TODO: one click handler for all .count buttons
</script>
</body>
</html>Show solution
$(".count").on("click", function () {
const $btn = $(this);
const clicks = ($btn.data("clicks") || 0) + 1;
$btn.data("clicks", clicks).text($btn.data("label") + " (" + clicks + ")");
console.log($btn.data("label"), clicks);
});Exercise 3 — Spoiler
Clicking Show spoiler should slide the hidden text down; clicking again slides it up. After the animation finishes, the button text must read Hide spoiler or Show spoiler to match the state.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
#spoiler { display: none; background: #222; color: #eee; padding: 10px; width: 260px; }
</style>
</head>
<body>
<button id="btn">Show spoiler</button>
<div id="spoiler">The butler did it. 🕵️</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// TODO: slide toggle + update the button text in the callback
</script>
</body>
</html>Show solution
$("#btn").on("click", function () {
$("#spoiler").stop(true, true).slideToggle(300, function () {
$("#btn").text($(this).is(":visible") ? "Hide spoiler" : "Show spoiler");
});
});Exercise 4 — Live profile card
As the user types a name and picks a colour, update the card: the name goes into #card-name (as text, safely), and the card's border colour follows the select. Also set the link's href to https://example.com/u/<name> in lowercase.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
#card { border: 4px solid #0769ad; border-radius: 8px; padding: 10px; width: 220px; margin-top: 8px; }
</style>
</head>
<body>
<input id="name" placeholder="Name">
<select id="color"><option>#0769ad</option><option>crimson</option><option>seagreen</option></select>
<div id="card"><b id="card-name">Anonymous</b><br><a id="card-link" href="#">profile</a></div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// TODO: update the card on "input" and "change"
</script>
</body>
</html>Show solution
function update() {
const name = $("#name").val().trim() || "Anonymous";
$("#card-name").text(name);
$("#card").css("border-color", $("#color").val());
$("#card-link").attr("href", "https://example.com/u/" + encodeURIComponent(name.toLowerCase()));
console.log("href:", $("#card-link").attr("href"));
}
$("#name").on("input", update);
$("#color").on("change", update);Exercise 5 — Shopping list
Typing an item and pressing Add (or Enter) appends a new <li> with a ✕ button. Clicking ✕ removes that item. Ignore empty input. Items added later must also be removable.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
li button { margin-left: 8px; border: 0; background: none; color: crimson; cursor: pointer; }
</style>
</head>
<body>
<form id="f"><input id="item" placeholder="e.g. eggs"> <button>Add</button></form>
<ul id="list"></ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// TODO: submit handler that appends; delegated handler that removes
</script>
</body>
</html>Show solution
$("#f").on("submit", function (e) {
e.preventDefault();
const text = $("#item").val().trim();
if (!text) return;
$("<li>").text(text).append($("<button type='button'>").text("✕")).appendTo("#list");
$("#item").val("").trigger("focus");
});
$("#list").on("click", "button", function () {
$(this).closest("li").remove();
console.log("items left:", $("#list li").length);
});Exercise 6 — Segmented control
Clicking an option makes it the only one with class on, and shows the chosen value in #choice.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
.seg span { display: inline-block; padding: 6px 12px; border: 1px solid #0769ad; cursor: pointer; }
.seg span.on { background: #0769ad; color: #fff; }
</style>
</head>
<body>
<div class="seg"><span>Day</span><span class="on">Week</span><span>Month</span></div>
<p>View: <b id="choice">Week</b></p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// TODO
</script>
</body>
</html>Show solution
$(".seg span").on("click", function () {
$(this).addClass("on").siblings().removeClass("on");
$("#choice").text($(this).text());
});Exercise 7 — Order total
Every row has a quantity input. Whenever any quantity changes, recalculate the line total (price × qty) in that row's .line cell and the grand total in #total. Use traversal from the changed input — no ids on rows.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
td { padding: 3px 8px; } input { width: 50px; }
</style>
</head>
<body>
<table id="order">
<tr data-price="2.5"><td>Coffee</td><td><input type="number" min="0" value="1"></td><td class="line"></td></tr>
<tr data-price="3"><td>Cake</td><td><input type="number" min="0" value="0"></td><td class="line"></td></tr>
<tr data-price="1.2"><td>Water</td><td><input type="number" min="0" value="2"></td><td class="line"></td></tr>
</table>
<p>Total: lt;b id="total">0.00</b></p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// TODO: update the line and the grand total on "input"; also run once at start
</script>
</body>
</html>Show solution
function recalc() {
let total = 0;
$("#order tr").each(function () {
const $row = $(this);
const line = $row.data("price") * (Number($row.find("input").val()) || 0);
$row.find(".line").text("quot; + line.toFixed(2));
total += line;
});
$("#total").text(total.toFixed(2));
}
$("#order").on("input", "input", function () {
const $row = $(this).closest("tr");
console.log($row.children().first().text(), "qty →", $(this).val());
recalc();
});
recalc();Exercise 8 — Tag filter
Clicking a tag button shows only the cards that have that tag in their data-tags (space-separated); All shows every card. Log how many cards are visible.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 13px; }
.card { display: inline-block; border: 1px solid #ccc; padding: 6px 10px; margin: 4px; border-radius: 6px; }
</style>
</head>
<body>
<button data-tag="">All</button> <button data-tag="js">js</button> <button data-tag="css">css</button> <button data-tag="html">html</button>
<div>
<div class="card" data-tags="js">Closures</div>
<div class="card" data-tags="css html">Flexbox</div>
<div class="card" data-tags="js html">DOM API</div>
<div class="card" data-tags="css">Grid</div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// TODO
</script>
</body>
</html>Show solution
$("button[data-tag]").on("click", function () {
const tag = $(this).data("tag");
const $cards = $(".card");
const $match = tag
? $cards.filter(function () { return $(this).data("tags").split(" ").includes(tag); })
: $cards;
$cards.not($match).fadeOut(150);
$match.fadeIn(150);
console.log(tag || "all", "→", $match.length, "visible");
});Using [data-tags~="js"] (the "word in a space-separated list" attribute selector) also works: $cards.filter('[data-tags~="' + tag + '"]').
Exercise 9 — Load a user list
When the button is clicked, load the JSON from usersUrl with $.getJSON, then render each user as <li>Name (city)</li>. Show "Loading…" while waiting and disable the button until the request finishes.
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; font-size: 14px">
<button id="load">Load users</button>
<ul id="users"></ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const usersUrl = "data:application/json," + encodeURIComponent(JSON.stringify([
{ name: "Ana", city: "Lisbon" }, { name: "Ben", city: "Lagos" }, { name: "Chloe", city: "Lyon" }
]));
// TODO
</script>
</body>
</html>Show solution
$("#load").on("click", function () {
const $btn = $(this).prop("disabled", true);
$("#users").html("<li>Loading…</li>");
$.getJSON(usersUrl)
.done(function (users) {
$("#users").empty().append($.map(users, u => $("<li>").text(u.name + " (" + u.city + ")")));
console.log("loaded", users.length, "users");
})
.fail(() => $("#users").html("<li>Could not load users</li>"))
.always(() => $btn.prop("disabled", false));
});Exercise 10 — Your own plugin
Write a chainable plugin $.fn.charCount(max) for text inputs/textareas. It inserts a <small> after each field showing used / max and turns the text red when the limit is exceeded. Test: $("textarea").charCount(20).css("width", "260px").
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif">
<textarea rows="2" placeholder="Short bio"></textarea><br>
<textarea rows="2" placeholder="Status"></textarea><br>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// TODO: define $.fn.charCount, then:
// $("textarea").charCount(20).css("width", "260px");
</script>
</body>
</html>Show solution
(function ($) {
$.fn.charCount = function (max = 100) {
return this.each(function () {
const $field = $(this);
const $info = $("<small>").insertAfter($field);
const update = () => {
const used = $field.val().length;
$info.text(" " + used + " / " + max).css("color", used > max ? "crimson" : "#666");
};
$field.on("input.charCount", update);
update();
});
};
})(jQuery);
$("textarea").charCount(20).css("width", "260px");Test yourself
In Exercise 5, why is the remove handler attached with $("#list").on("click", "button", …)?
- Because buttons cannot have click handlers
- Because the items are created later, so delegation is needed
- To make the buttons faster
- Because
#listis a form
Which call in Exercise 6 makes the clicked option the only active one?
$(this).toggleClass("on")$(this).addClass("on").siblings().removeClass("on")$(".seg span").addClass("on")$(this).siblings().addClass("on")
Why does the plugin in Exercise 10 use return this.each(...)?
eachis required to define plugins- It handles every matched element and returns the jQuery object for chaining
- It makes the plugin asynchronous
- It prevents the plugin from running twice