Question
I want to understand how to control an element's visibility in jQuery using .hide(), .show(), and .toggle(). I also want to know how to check whether an element is currently visible or hidden.
Short Answer
By the end of this page, you will know how jQuery hides and shows elements, how to toggle visibility, and how to test whether an element is visible or hidden using selectors like :visible and :hidden and methods like .is(). You will also see practical examples, common mistakes, and how this pattern appears in real projects.
Concept
In jQuery, visibility control means changing whether an element is displayed on the page.
The most common methods are:
.hide()— hides the element.show()— shows the element.toggle()— switches between hidden and visible
To check visibility, jQuery commonly uses:
$(selector).is(':visible')$(selector).is(':hidden')
These checks are useful when your code needs to decide what to do next. For example:
- open or close a dropdown
- show validation messages only when needed
- reveal extra form fields
- switch text like Show details / Hide details
Why this matters in real programming:
- User interfaces often react to clicks and state changes.
- Your code needs a reliable way to know what the user currently sees.
- Visibility checks help you avoid duplicated UI logic and make interactions predictable.
A simple example:
if ($('#panel').is(':hidden')) {
$('#panel').show();
}
This says: if the panel is currently hidden, show it.
In jQuery, visibility usually depends on whether the element takes up space in the layout. In practice, :visible and :hidden are the most common tools for this kind of check.
Mental Model
Think of a web page like a stage.
.show()puts an actor back on stage..hide()removes the actor from the stage..toggle()checks whether the actor is on stage and flips the state.is(':visible')asks, "Can the audience currently see this actor?"is(':hidden')asks, "Is this actor currently off stage?"
So visibility checks are like looking at the stage before deciding what the next action should be.
Syntax and Examples
Core syntax
$('#box').hide();
$('#box').show();
$('#box').toggle();
$('#box').is(':visible');
$('#box').is(':hidden');
Example: toggle a message
$('#toggleButton').on('click', function () {
$('#message').toggle();
});
This switches #message between visible and hidden every time the button is clicked.
Example: check before acting
if ($('#message').is(':visible')) {
console.log('The message is visible');
} else {
console.log('The message is hidden');
}
This is useful when your code should behave differently depending on the current UI state.
Example: update button text
$('#toggleButton').on('click', function () {
$('#details').toggle();
if ($('#details').is(':visible')) {
$(this).text('Hide details');
} else {
$(this).text('Show details');
}
});
Here, jQuery not only toggles the element but also updates the button label to match the current state.
Step by Step Execution
Traceable example
$('#toggleButton').on('click', function () {
if ($('#panel').is(':hidden')) {
$('#panel').show();
} else {
$('#panel').hide();
}
});
What happens step by step
- jQuery finds the element with id
toggleButton. - It attaches a click event handler to that button.
- When the user clicks the button, the function runs.
- jQuery checks
$('#panel').is(':hidden'). - If the panel is hidden:
$('#panel').show()runs- the panel becomes visible
- Otherwise:
$('#panel').hide()runs- the panel becomes hidden
Example state trace
Assume #panel starts hidden.
- First click:
is(':hidden')istrue→.show()runs - Second click:
is(':hidden')isfalse→.hide()runs - Third click:
is(':hidden')istrueagain →.show()runs
This is the same basic idea as .toggle(), but written out manually so you can clearly see the decision-making logic.
Real World Use Cases
Common practical uses
Expand/collapse sections
FAQ items, settings panels, and help sections often hide content until the user asks to see it.
$('.faq-question').on('click', function () {
$(this).next('.faq-answer').toggle();
});
Form field logic
Show extra fields only if the user selects a certain option.
$('#hasCompany').on('change', function () {
if ($(this).is(':checked')) {
$('#companyFields').show();
} else {
$('#companyFields').hide();
}
});
Validation messages
Hide error messages until validation fails.
if ($('#email').val() === '') {
$('#emailError').show();
} else {
$('#emailError').hide();
}
Menus and dropdowns
Navigation menus often appear only after a click or hover.
Loading states
A loading spinner may be shown while a request is in progress and hidden afterward.
Real Codebase Usage
In real projects, developers usually use visibility methods as part of UI state handling.
Common patterns
Guard clauses
Only show or hide when needed.
if ($('#modal').is(':visible')) {
return;
}
$('#modal').show();
This avoids unnecessary work or repeated UI actions.
Early returns
Stop logic when the current state already matches the goal.
function openSidebar() {
if ($('#sidebar').is(':visible')) return;
$('#sidebar').show();
}
Validation and feedback
Developers often combine visibility with error handling.
function validateName() {
if ($('#name').val().trim() === '') {
$('#nameError').show();
return false;
}
$('#nameError').hide();
return true;
}
Event-driven UI updates
Visibility is often changed in click, submit, input, and AJAX callbacks.
$('#loadButton').on('click', function () {
$('#spinner').show();
$.get('/data', function (response) {
$('#result').text(response);
$('#spinner').hide();
});
});
Keeping UI text in sync
A common pattern is changing labels, icons, or classes after a visibility change.
$('#menuButton').on('click', function () {
$('#menu').toggle();
$(this).text($('#menu').is(':visible') ? 'Close menu' : 'Open menu');
});
In larger codebases, developers may prefer class-based approaches for styling, but jQuery visibility methods are still common in existing applications and smaller scripts.
Common Mistakes
1. Checking the jQuery object itself instead of visibility
Broken code:
if ($('#box')) {
console.log('Visible');
}
Why this is wrong:
$('#box')returns a jQuery object.- That object can exist even if the element is hidden.
- This does not test visibility.
Correct code:
if ($('#box').is(':visible')) {
console.log('Visible');
}
2. Forgetting that .toggle() changes state immediately
Broken thinking:
$('#box').toggle();
if ($('#box').is(':hidden')) {
console.log('Box was hidden');
}
Why this is confusing:
- The check happens after the toggle.
- You are checking the new state, not the old one.
Better approach:
var wasHidden = $('#box').is(':hidden');
$('#box').toggle();
console.log(wasHidden);
3. Using raw DOM properties with jQuery without care
Possible code:
if ($('#box').style.display === 'none') {
// incorrect
}
Why this is wrong:
$('#box')is a jQuery object, not a raw DOM element..style.displaydoes not work directly on a jQuery object.
Correct jQuery approach:
if ($('#box').is(':hidden')) {
// correct
}
4. Assuming hidden always means display: none only
Visibility in jQuery can depend on layout and rendering rules, not just a single inline style.
Safer approach:
- Use
:visibleand:hiddenfor jQuery-based visibility checks. - Use
.css('display')only when you specifically need the CSS display value.
5. Selecting the wrong element
Broken code:
$('.panel').is(':hidden')
Why this can be a problem:
- If multiple elements match
.panel, the result applies to the first matched element. - Beginners sometimes expect it to check all of them.
Better options:
$('.panel').each(function () {
console.log($(this).is(':hidden'));
});
Or target a specific element more clearly.
6. Forgetting the element may not exist
if ($('#missingBox').is(':visible')) {
// may not behave as expected for a missing element
}
Safer pattern:
if ($('#missingBox').length && $('#missingBox').is(':visible')) {
// element exists and is visible
}
Comparisons
Visibility methods and checks
| jQuery feature | Purpose | Changes state? | Returns a boolean? |
|---|---|---|---|
.hide() | Hide an element | Yes | No |
.show() | Show an element | Yes | No |
.toggle() | Switch visibility | Yes | No |
.is(':hidden') | Test whether hidden | No | Yes |
.is(':visible') | Test whether visible | No | Yes |
.toggle() vs manual if/else
| Approach | Best when | Example |
|---|---|---|
.toggle() | You only want to flip visibility | $('#box').toggle(); |
if/else with .is() | You need different logic for each state | if ($('#box').is(':hidden')) { ... } |
.is(':hidden') vs checking CSS directly
| Approach | Recommended? | Why |
|---|---|---|
$('#box').is(':hidden') | Yes | Clear and designed for visibility checks in jQuery |
$('#box').css('display') === 'none' | Sometimes | Useful only if you specifically care about the display property |
element.style.display === 'none' | Less ideal in jQuery code | Only checks inline style and mixes raw DOM with jQuery |
jQuery methods vs class-based styling
| Approach | Strength | Trade-off |
|---|---|---|
.show() / .hide() | Simple and quick | Less flexible for complex styling systems |
| Toggling a CSS class | Better for reusable design patterns | Requires CSS setup |
Example class-based approach:
$('#box').toggleClass('hidden');
.hidden {
display: none;
}
This pattern is often preferred in modern projects when styling rules are managed through CSS classes.
Cheat Sheet
Quick reference
$('#box').hide(); // hide
$('#box').show(); // show
$('#box').toggle(); // switch state
$('#box').is(':hidden'); // true if hidden
$('#box').is(':visible'); // true if visible
Common patterns
Show only if hidden
if ($('#box').is(':hidden')) {
$('#box').show();
}
Hide only if visible
if ($('#box').is(':visible')) {
$('#box').hide();
}
Toggle on click
$('#button').on('click', function () {
$('#box').toggle();
});
Update text based on visibility
$('#button').text($('#box').is(':visible') ? 'Hide' : 'Show');
Rules to remember
.hide(),.show(), and.toggle()change the UI..is(':hidden')and.is(':visible')only check state.$('#box')by itself does not mean the element is visible.- If multiple elements match a selector,
.is()checks based on the matched set, often leading beginners to think it checks every element individually. - Use
.lengthif you also need to confirm the element exists.
Useful existence check
if ($('#box').length > 0) {
// element exists
}
FAQ
How do I check if an element is hidden in jQuery?
Use:
$('#element').is(':hidden')
It returns true if the element is hidden.
How do I check if an element is visible in jQuery?
Use:
$('#element').is(':visible')
It returns true if the element is visible.
What is the difference between .toggle() and .is(':hidden')?
.toggle()changes visibility..is(':hidden')only checks visibility.
One acts, the other tests.
Should I use .css('display') === 'none' instead?
Usually, no. In jQuery code, :hidden and :visible are clearer and more reliable for checking visibility.
Does .hide() remove the element from the DOM?
No. It only hides the element visually. The element still exists in the page structure.
Can I use .toggle() in a click handler?
Yes. That is one of the most common uses.
$('#button').on('click', function () {
$('#panel').toggle();
});
Why does if ($('#box')) not work for visibility?
Because $('#box') returns a jQuery object, not a visibility check. Use .is(':visible') or .is(':hidden') instead.
Mini Project
Description
Build a small details panel interaction where a button shows and hides extra information. This demonstrates how to use .toggle(), .show(), .hide(), and .is(':visible') together in a realistic UI pattern.
Goal
Create a button that toggles a details section and updates its own text based on whether the section is visible.
Requirements
["Create a button and a details section in HTML.","Hide the details section when the page first loads.","When the button is clicked, toggle the details section.","Change the button text to match the current state: Show details or Hide details."]
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.