Categories: Development

Show & hide Bootstrap modal with jQuery

Opening and closing a Bootstrap modal using the traditional button method and then with jQuery targeting with a button click.

CodePen example.

Traditional way

Opening (showing) the modal the traditional way with data-toggle and data-target

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#theModal">Open</button>

Closing (hiding) the modal with data-dismiss

<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>

With jQuery

Or you can create buttons with a click function to show the modal or hide the modal.

<button type="button" class="btn btn-success" id="modalOpen">Open</button>

<button type="button" class="btn btn-warning" id="modalClose">Close</button>

On document ready wait for the button clicks:

$(document).ready(function () {
    $("#modalOpen").click(function () {
        $('#theModal').modal('show');
    });
    
    $("#modalClose").click(function () {
        $('#theModal').modal('hide');
    });
});

toggle can also be used, this will show if hidden and hide if shown. However, using this method means you don’t always know or have control of what state the modal is in.

Check if modal is shown

A method to check if a modal is active (shown) or not:

if ($("#theModal").hasClass("show")) {
    alert('is shown');
}

This checks if the modal has the class show.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago