All jQuery Exercises
Write jQuery code to change the text of a heading when the page loads
Description: The page has a heading with the text “Loading…”. When the page is ready, change it to “Welcome to jQuery”.
Hint:
- Use
$(document).ready()and the.text()method.
HTML of the page
<h1 id="title">Loading...</h1>
Solution
$(function () {
$('#title').text('Welcome to jQuery');
});
<h1 id="title">Welcome to jQuery</h1>
How it works
- The ready function waits until the DOM is built, so the heading exists.
.text()with a value replaces the text of the element.
Read Document Ready and Set Content.
Write jQuery code to hide a paragraph when a button is clicked
Description: There is a button and a paragraph. When the button is clicked, hide the paragraph.
Hint:
- Attach a click event to the button with
.on('click', ...)and use.hide().
HTML of the page
<button id="hide-btn">Hide the text</button>
<p id="para">This paragraph will be hidden.</p>
Solution
$('#hide-btn').on('click', function () {
$('#para').hide();
});
$('#hide-btn').click(); // we simulate a click, to see the result
<button id="hide-btn">Hide the text</button>
<p id="para" style="display: none;">This paragraph will be hidden.</p>
How it works
- The handler runs on click, and
hide()setsdisplay: noneon the paragraph. - The last line simulates the click, so we can show the result here.
Read jQuery Events and Effects.
Write jQuery code to show and hide a panel with one button
Description: One button must open the panel if it is closed, and close it if it is open.
Hint:
- Use
.toggle()or.slideToggle().
HTML of the page
<button id="btn">Open / Close</button>
<div id="panel" style="display:none">Panel content</div>
Solution
$('#btn').on('click', function () {
$('#panel').slideToggle(300);
});
$('#btn').click();
console.log('after click 1: ' + $('#panel').css('display'));
$('#btn').click();
console.log('after click 2: ' + $('#panel').css('display'));
after click 1: block
after click 2: none
How it works
slideToggle()slides the panel down if it is hidden, and up if it is visible.- The panel starts hidden, so the first click opens it.
Read Fade and Slide Effects.
Write jQuery code to change the color and size of all paragraphs
Description: Make the text of all paragraphs blue and set the font size to 18px.
Hint:
- Pass an object to
.css()to set many properties.
HTML of the page
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
Solution
$('p').css({
'color': 'blue',
'font-size': '18px'
});
<p style="color: blue; font-size: 18px;">First paragraph</p>
<p style="color: blue; font-size: 18px;">Second paragraph</p>
<p style="color: blue; font-size: 18px;">Third paragraph</p>
How it works
- The selector
pfinds all three paragraphs, and the method works on every one of them without a loop.
Read CSS Methods.
Write jQuery code to highlight the clicked list item
Description: When you click a list item it must get the class active, and the other items must lose it.
Hint:
- Use
$(this),.addClass()and.siblings().removeClass().
HTML of the page
<ul id="menu">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
Solution
$('#menu li').on('click', function () {
$(this).addClass('active').siblings().removeClass('active');
});
$('#menu li').eq(2).click(); // click on "Contact"
<ul id="menu">
<li class="">Home</li>
<li>About</li>
<li class="active">Contact</li>
</ul>
How it works
$(this)is the clicked item.siblings()are the other items of the same list.- After the click on Contact, only that item has the class
active.
Read CSS Classes and Siblings.
Write jQuery code to count the items of a list
Description: Count the items of the list and show “Total items: N” in the paragraph.
Hint:
- A jQuery object has a
lengthproperty.
HTML of the page
<ul id="fruits">
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
<li>Orange</li>
</ul>
<p id="count"></p>
Solution
var total = $('#fruits li').length;
$('#count').text('Total items: ' + total);
<p id="count">Total items: 4</p>
How it works
$('#fruits li')selects all list items, andlengthis the number of selected elements.
Read jQuery Selectors.
Write jQuery code to add a new list item from a text field
Description: When the user clicks “Add”, the text of the input must be added as a new list item, and the input must be cleared. Do not add empty text.
Hint:
- Use
.val(),$('<li>').text(...)and.append().
HTML of the page
<input type="text" id="task" value="Buy milk">
<button id="add">Add</button>
<ul id="todo"></ul>
Solution
$('#add').on('click', function () {
var text = $('#task').val().trim();
if (text === '') {
return;
}
$('<li>').text(text).appendTo('#todo');
$('#task').val('');
});
$('#add').click();
<input type="text" id="task" value="Buy milk">
<button id="add">Add</button>
<ul id="todo">
<li>Buy milk</li>
</ul>
How it works
trim()removes spaces, so an empty text is not added.- We create the
liand set the text with.text(), which is safe against HTML in the input. .val('')clears the field.
Read Add Elements.
Write jQuery code to remove a list item when it is clicked
Description: Clicking on the “Delete” button of an item must remove that item. It must also work for the new items.
Hint:
- Use a delegated event on the list and
.closest('li').remove().
HTML of the page
<ul id="list">
<li>Item 1 <button class="del">Delete</button></li>
<li>Item 2 <button class="del">Delete</button></li>
</ul>
Solution
$('#list').on('click', '.del', function () {
$(this).closest('li').remove();
});
// a new item added later
$('#list').append('<li>Item 3 <button class="del">Delete</button></li>');
$('.del').eq(0).click(); // delete the first
$('.del').eq(1).click(); // delete what is now the second (the new one)
console.log('items left: ' + $('#list li').length);
items left: 1
<ul id="list">
<li>
Item 2
<button class="del">Delete</button>
</li>
</ul>
How it works
- The handler is on the list, so it also works for the items which are added later.
closest('li')finds the item of the clicked button.
Read Event Delegation and Remove Elements.
Write jQuery code to change the image source when a thumbnail is clicked
Description: The thumbnails have the big image address in a data-big attribute. Clicking a thumbnail must show the big image.
Hint:
- Use
.data('big')and.attr().
HTML of the page
<img id="big" src="images/one-big.jpg" alt="One">
<img class="thumb" src="images/one-small.jpg" alt="One" data-big="images/one-big.jpg">
<img class="thumb" src="images/two-small.jpg" alt="Two" data-big="images/two-big.jpg">
Solution
$('.thumb').on('click', function () {
$('#big').attr({
src: $(this).data('big'),
alt: $(this).attr('alt')
});
});
$('.thumb').eq(1).click();
<img id="big" src="images/two-big.jpg" alt="Two">
How it works
.data('big')reads thedata-bigattribute of the clicked thumbnail..attr({...})sets two attributes at the same time.
Read Get Content and Set Content.
Write jQuery code to show the text typed in an input field
Description: Whatever the user types in the field must also appear in the paragraph below it, at once.
Hint:
- Use the
inputevent,.val()and.text().
HTML of the page
<input type="text" id="name" placeholder="Type your name">
<p>Hello, <span id="show"></span></p>
Solution
$('#name').on('input', function () {
$('#show').text($(this).val());
});
$('#name').val('Anita').trigger('input'); // simulate the typing
<p>Hello, <span id="show">Anita</span></p>
How it works
- The
inputevent fires on every change of the text, also when the user pastes. - We use
.text()to show the value safely.
Write jQuery code to validate that a field is not empty before submit
Description: If the name field is empty, stop the form and show the message “Name is required”.
Hint:
- Use the
submitevent,e.preventDefault()and.val().trim().
HTML of the page
<form id="form">
<input type="text" id="name" value=" ">
<span id="error"></span>
<button type="submit">Send</button>
</form>
Solution
$('#form').on('submit', function (e) {
if ($('#name').val().trim() === '') {
e.preventDefault();
$('#error').text('Name is required');
} else {
$('#error').text('');
}
});
$('#form').trigger('submit');
console.log($('#error').text());
Name is required
How it works
- The field has only spaces, so after
trim()it is empty. preventDefault()stops the browser from sending the form.
Read jQuery Forms.
Write jQuery code to show the remaining characters of a textarea
Description: The textarea allows 50 characters. Show “N characters left” below it.
Hint:
- Use the length of
.val()in theinputevent.
HTML of the page
<textarea id="msg" maxlength="50"></textarea>
<p id="left">50 characters left</p>
Solution
var max = 50;
$('#msg').on('input', function () {
var left = max - $(this).val().length;
$('#left').text(left + ' characters left');
});
$('#msg').val('Hello jQuery world').trigger('input');
<p id="left">32 characters left</p>
How it works
- The text has 18 characters, so 32 are left.
- The
maxlengthattribute in the HTML stops the typing at 50.
Read jQuery Forms.
Write jQuery code for a “select all” checkbox
Description: A master checkbox must check or uncheck all the item checkboxes. If one item is unchecked, the master must be unchecked.
Hint:
- Use
.prop('checked', ...)and compare the count of all and checked boxes.
HTML of the page
<input type="checkbox" id="all"> Select all
<input type="checkbox" class="item"> A
<input type="checkbox" class="item"> B
<input type="checkbox" class="item"> C
Solution
$('#all').on('change', function () {
$('.item').prop('checked', this.checked);
});
$('.item').on('change', function () {
var allChecked = $('.item:checked').length === $('.item').length;
$('#all').prop('checked', allChecked);
});
$('#all').prop('checked', true).trigger('change');
console.log('checked items: ' + $('.item:checked').length);
$('.item').eq(1).prop('checked', false).trigger('change');
console.log('master checked: ' + $('#all').prop('checked'));
checked items: 3
master checked: false
How it works
- The master sets the
checkedproperty of all items. - When one item changes, we compare the number of checked items with the total.
Read Get Content (attr vs prop).
Write jQuery code to make a simple accordion
Description: Clicking on a question must open its answer, and close the other open answers.
Hint:
- Use
.next(),.slideToggle()and.siblings()or.not().
HTML of the page
<div id="faq">
<h3>Question 1</h3><p style="display:none">Answer 1</p>
<h3>Question 2</h3><p style="display:none">Answer 2</p>
<h3>Question 3</h3><p style="display:none">Answer 3</p>
</div>
Solution
$('#faq h3').on('click', function () {
var $answer = $(this).next('p');
$('#faq p').not($answer).slideUp();
$answer.slideToggle();
});
$('#faq h3').eq(0).click();
$('#faq h3').eq(1).click();
$('#faq p').each(function (i) {
console.log('Answer ' + (i + 1) + ': ' + $(this).css('display'));
});
Answer 1: none
Answer 2: block
Answer 3: none
How it works
- The first click opens answer 1. The second click opens answer 2 and closes answer 1.
.not($answer)selects all the other answers.
Read Fade and Slide Effects.
Write jQuery code to make simple tabs
Description: There are three tab buttons. Clicking one must show only its content and mark the button as active.
Hint:
- Link each button to its content with a
data-tabattribute.
HTML of the page
<div id="tabs">
<button class="tab active" data-tab="t1">Tab 1</button>
<button class="tab" data-tab="t2">Tab 2</button>
<button class="tab" data-tab="t3">Tab 3</button>
</div>
<div id="t1" class="content">Content 1</div>
<div id="t2" class="content" style="display:none">Content 2</div>
<div id="t3" class="content" style="display:none">Content 3</div>
Solution
$('.tab').on('click', function () {
$('.tab').removeClass('active');
$(this).addClass('active');
$('.content').hide();
$('#' + $(this).data('tab')).show();
});
$('.tab').eq(2).click();
$('.content').each(function () {
console.log(this.id + ': ' + $(this).css('display'));
});
t1: none
t2: none
t3: block
How it works
- The
data-tabvalue is the id of the content to show. - First all contents are hidden, then the right one is shown.
Read CSS Classes and Effects.
Write jQuery code to filter a list while typing in a search box
Description: When the user types in the search box, show only the list items which contain the text. The search must not depend on upper or lower case.
Hint:
- Use
.toggle(condition)andindexOf()on lowercase text.
HTML of the page
<input type="text" id="search">
<ul id="names">
<li>Anita</li>
<li>Ravi</li>
<li>Maya</li>
<li>Manish</li>
</ul>
Solution
$('#search').on('input', function () {
var term = $(this).val().toLowerCase();
$('#names li').each(function () {
var match = $(this).text().toLowerCase().indexOf(term) !== -1;
$(this).toggle(match);
});
});
$('#search').val('MA').trigger('input');
$('#names li').each(function () {
console.log($(this).text() + ': ' + $(this).css('display'));
});
Anita: none
Ravi: none
Maya: list-item
Manish: list-item
How it works
- The search text “MA” matches “Maya” and “Manish”.
.toggle(true)shows an element and.toggle(false)hides it.
Read jQuery each() and Effects.
Write jQuery code to find the total of a table column
Description: Add all prices of the table and show the total in the last row.
Hint:
- Use
.each(),parseFloat()and the.text()method.
HTML of the page
<table id="cart">
<tr><td>Pen</td><td class="price">10</td></tr>
<tr><td>Notebook</td><td class="price">45.50</td></tr>
<tr><td>Eraser</td><td class="price">5</td></tr>
<tr><td>Total</td><td id="total"></td></tr>
</table>
Solution
var total = 0;
$('#cart .price').each(function () {
total += parseFloat($(this).text());
});
$('#total').text(total.toFixed(2));
console.log('Total = ' + total);
Total = 60.5
<td id="total">60.50</td>
How it works
each()runs for every price cell, and we add the number to the total.toFixed(2)shows two digits after the decimal point.
Read jQuery each().
Write jQuery code to add alternate row colors to a table
Description: Give the class even to the rows at position 2, 4, … and the class odd to the others.
Hint:
:nth-child()in the selector, or the index ofeach().
HTML of the page
<table id="t">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
<tr><td>Row 4</td></tr>
</table>
Solution
$('#t tr:nth-child(even)').addClass('even');
$('#t tr:nth-child(odd)').addClass('odd');
<table id="t">
<tbody>
<tr class="odd">
<td>Row 1</td>
</tr>
<tr class="even">
<td>Row 2</td>
</tr>
<tr class="odd">
<td>Row 3</td>
</tr>
<tr class="even">
<td>Row 4</td>
</tr>
</tbody>
</table>
How it works
:nth-child(even)is a CSS selector, so it is fast and standard.- The classes are used by CSS for the colors.
Read jQuery Selectors.
Write jQuery code to load JSON data with Ajax and show it in a list
Description: The file courses.json has a list of courses. Load it and show the titles in the list.
Hint:
- Use
$.getJSON()and$.each().
The JSON file and the HTML
[
{ "id": 1, "title": "HTML Basics" },
{ "id": 2, "title": "CSS Layouts" },
{ "id": 3, "title": "jQuery Tutorial" }
]
<ul id="courses"></ul>
Solution
$.getJSON('courses.json')
.done(function (courses) {
$.each(courses, function (i, course) {
$('<li>').text(course.title).appendTo('#courses');
});
})
.fail(function () {
$('#courses').text('Could not load the courses');
});
<ul id="courses">
<li>HTML Basics</li>
<li>CSS Layouts</li>
<li>jQuery Tutorial</li>
</ul>
How it works
$.getJSON()loads the file and parses it into an array.- We create a list item with
.text()for each course. - The
fail()handler shows a message if the file cannot be loaded.
Read jQuery Ajax.
Write jQuery code to submit a form with Ajax
Description: Submit the contact form in the background, and show the message from the server below the form.
Hint:
- Use
e.preventDefault(),.serialize()and$.ajax().
HTML of the page
<form id="contact" action="send" method="post">
<input type="text" name="name" value="Anita">
<input type="email" name="email" value="anita@example.com">
<button type="submit">Send</button>
</form>
<p id="result"></p>
Solution
$('#contact').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: $(this).attr('method'),
data: $(this).serialize(),
dataType: 'json'
}).done(function (res) {
$('#result').text('Server received: ' + res.received);
}).fail(function () {
$('#result').text('Sorry, there was an error.');
});
});
$('#contact').trigger('submit');
<p id="result">Server received: name=Anita&email=anita%40example.com</p>
How it works
- The data is sent as
name=Anita&email=anita%40example.com. Here the test server only repeats it. - The page is not reloaded, and the result is shown in the paragraph.
Read jQuery Forms and jQuery Ajax.