This guide demonstrates how to use jQuery to create a simple toggle effect. The example includes a button to show or hide a div and a link inside the div to close it.
Code Example
Here’s a straightforward example of how to use jQuery for toggling a div:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Learn how to create a simple toggle effect with jQuery. This guide includes a concise code example and clear explanations.">
    <meta name="keywords" content="jQuery, toggle, JavaScript, web development">
    <title>jQuery Toggle Effect Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    $(document).ready(function() {
        $("#toggleButton").click(function() {
            $("#toggleDiv").slideToggle();
        });
        $("#toggleDiv a").click(function() {
            $("#toggleDiv").slideUp();
        });
    });
    </script>
</head>
<body>
    <button id="toggleButton">Toggle Div</button>
    <div id="toggleDiv" style="display: none;">
        <a href="#">Close</a>
        <p>This is the content inside the div.</p>
    </div>
</body>
</html>How It Works
This code uses jQuery to manage the visibility of a div:
- Include jQuery: The script tag includes jQuery from a CDN.
- Toggle Button: The button with ID toggleButtontoggles the visibility of the div with IDtoggleDiv.
- Close Link: The link inside toggleDivhides the div when clicked.
Comments
Post a Comment