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() sets display: none on the paragraph.
  • The last line simulates the click, so we can show the result here.

Read jQuery Events and Effects.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.