jQuery Events
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
HTML after the code runs
<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 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"
HTML after the code runs
<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 clicks of a button
Description: Show the number of clicks of the “Count” button. A second button must set the count back to 0.
Hint:
- Keep the count in a variable and update the text in each click.
HTML of the page
<button id="count">Count</button>
<button id="reset">Reset</button>
<p>Clicks: <span id="n">0</span></p>
Solution
var clicks = 0;
$('#count').on('click', function () {
clicks++;
$('#n').text(clicks);
});
$('#reset').on('click', function () {
clicks = 0;
$('#n').text(clicks);
});
$('#count').click().click().click();
console.log('after 3 clicks: ' + $('#n').text());
$('#reset').click();
console.log('after reset: ' + $('#n').text());
Console output
after 3 clicks: 3
after reset: 0
How it works
- The variable keeps the state outside of the handlers, so both handlers can use it.
Read jQuery Events.