How to use jQuery to hide an element on a button click



Image not found!!


Hiding an element upon a button click in jQuery involves employing the hide() method. This method allows you to dynamically manipulate the visibility of HTML elements on your webpage. Consider a basic scenario where you have a button and an element you want to hide. Through jQuery, you can bind a click event to the button and execute the hide() method on the target element. The method essentially alters the CSS display property to none, making the element invisible. Here's a straightforward example:



STEP 1 : Include jQuery in your HTML file. You can include it from a CDN or download it and host it locally. For example, using a CDN

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

STEP 2 : Create your HTML structure with the element you want to hide and a button to trigger the hiding action

<div id="elementToHide" class="" style="color: green; font-size: 38px; font-weight: 700;">This is the element to hide</div>
<button id="hideButton" class="btn btn-danger">Hide Element</button>

STEP 3 : Write jQuery code to hide the element when the button is clicked

<script>
        $(document).ready(function () {
            $("#hideButton").click(function () {
                $("#elementToHide").hide();
            });
        });
    </script>


Run this code : Here is the full code, you can run

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Hide Element</title>
</head>

<body>

    <div class="container">
        <div class="row">
            <div class="col-lg-12 text-center mt-5">
                <div id="elementToHide" class="" style="color: green; font-size: 38px; font-weight: 700;">This is the element to hide</div>
                <button id="hideButton" class="btn btn-danger">Hide Element</button>
            </div>
        </div>
    </div>


    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
        crossorigin="anonymous"></script>
    <script>
        $(document).ready(function () {
            $("#hideButton").click(function () {
                $("#elementToHide").hide();
            });
        });
    </script>
</body>

</html>