Script to Close a Block on Click: Implementation Using jQuery

July 15, 2024

Web development often requires creating interactive elements such as blocks that can be closed by clicking a "close" button or outside the block itself. In this article, we will look at a simple way to implement this functionality using the jQuery library and the .hide() method.

Creating the HTML Structure

For example, let's consider a block that needs to be closed when clicking a button with the class .close:

<div class="block">
    Block Content
    <div class="close">close</div>
</div>   

Including jQuery

Before using the script, make sure you have included the jQuery library in your page. This can be done with the following line of code:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>   

Creating the Script to Close the Block

Now let's create the script that will hide the block when clicking the button with the class .close:

<script>
    jQuery(document).ready(function($) {
        $('.close').click(function () {
            $('.block').hide();
        });
    });
</script>

This script uses the click event for the element with the class .close. On each click, the script calls the .hide() method for the element with the class .block, which hides the block.

Closing the Block When Clicking Outside of It

If you want the block to also close when clicking outside of it, add the following code to your script:

<script>
    jQuery(document).ready(function($) {
        $('body, .close').click(function (e) {
            if (!$(e.target).closest('.block').length) {
                $('.block').hide();
            }
        });
    });
</script>

This code adds an additional click event handler for the body and .close elements. If the click occurred outside the block (checked using .closest('.block')), the block will be hidden.

Conclusion

Thus, you can easily add the functionality of closing a block when clicking a button or outside the block using a simple jQuery-based script. We hope this article was helpful to you in implementing similar functionality on your website.

Ready to assist in creating a new website starting from $250 or making changes to an existing one.
Contact us for professional support.

Contact me on Telegram: @lb_user Write by e-mail: [email protected]

Add comment