To show, hide, and toggle elements in JavaScript, you can manipulate the
style property of the HTML elements or use a library like jQuery for simplified animations. Here's an example using both plain JavaScript and jQuery:
Plain JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Show, Hide, Toggle in JavaScript</title>
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<button onclick="showElement()">Show Element</button>
<button onclick="hideElement()">Hide Element</button>
<button onclick="toggleElement()">Toggle Element</button>
<div id="myElement" class="hidden">
This is the element to show, hide, and toggle.
</div>
<script>
function showElement() {
var element = document.getElementById("myElement");
element.style.display = "block";
}
function hideElement() {
var element = document.getElementById("myElement");
element.style.display = "none";
}
function toggleElement() {
var element = document.getElementById("myElement");
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
</script>
</body>
</html>
jQuery:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Show, Hide, Toggle with jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<button onclick="showElement()">Show Element</button>
<button onclick="hideElement()">Hide Element</button>
<button onclick="toggleElement()">Toggle Element</button>
<div id="myElement" style="display: none;">
This is the element to show, hide, and toggle.
</div>
<script>
function showElement() {
$("#myElement").show();
}
function hideElement() {
$("#myElement").hide();
}
function toggleElement() {
$("#myElement").toggle();
}
</script>
</body>
</html>
In the examples above:
The display property of the element is modified directly using JavaScript.
In jQuery, the show(), hide(), and
toggle() methods are used to achieve the same effects.
Choose the method that best fits your project requirements and coding style.
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To show, hide, and toggle elements in JavaScript, you can manipulate the style property of the HTML elements or use a library like jQuery for simplified animations. Here's an example using both plain JavaScript and jQuery:
Plain JavaScript:
jQuery:
In the examples above:
Choose the method that best fits your project requirements and coding style.