jQuery is a popular JavaScript library that simplifies working with HTML documents, handling events, and manipulating the DOM (Document Object Model). Below is a simple example of a jQuery function that toggles the visibility of an HTML element when a button is clicked:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Example</title>
<!-- Include jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="toggleButton">Toggle Element</button>
<div id="elementToToggle" style="display: none;">
This is the element to toggle.
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript (script.js):
$(document).ready(function() {
// This function will run when the document is ready
// Find the button element with the id "toggleButton" and add a click event handler
$("#toggleButton").click(function() {
// Find the element with the id "elementToToggle" and toggle its visibility
$("#elementToToggle").toggle();
});
});
In this example:
- We include the jQuery library using a
<script>
tag in the HTML's<head>
. - We have a button with the ID "toggleButton" and a
<div>
with the ID "elementToToggle" that is initially hidden (usingstyle="display: none;"
). - In the JavaScript file (script.js), we use the
$(document).ready()
function to ensure that the code inside it only runs when the HTML document is fully loaded. - We select the button and add a click event handler using
$("#toggleButton").click(...)
. - In the click event handler, we select the element with the ID "elementToToggle" and use the
toggle()
function to toggle its visibility.
When the "Toggle Element" button is clicked, the "elementToToggle" div will appear or disappear, depending on its current visibility state.
This is a simple example, and jQuery offers many more features for working with HTML and handling events.
2 Comments
Great
ReplyDeleteTnanks
Delete