📜  jquery on modal show - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:11.118000             🧑  作者: Mango

jQuery On Modal Show - JavaScript

Modal windows are an important part of a user-friendly website. They can help to provide contextual information, allow users to make choices, or to gather important data. When a modal window is displayed, it's important that other parts of the page don't interfere with it. In this guide, we'll look at how to use jQuery to handle events that occur when a modal is shown.

How to use jQuery 'on' with modal show events

To trigger code or an alert when a modal is shown in jQuery, you can use the 'on' method. You'll need to attach the 'shown.bs.modal' event to your modal's HTML element to fire an event when it pops up on the screen.

Here's an example:

$('#myModal').on('shown.bs.modal', function () {
  alert('Modal shown!');
});

In the above example, '#myModal' represents the selector of the specific modal element you want to watch for the 'shown.bs.modal' event.

Code example

Here is a sample code snippet that demonstrates the use of the above example:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery On Modal Show Example</title>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
 
<div class="container">
 
  <h2>jQuery On Modal Show Example</h2>
 
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Launch demo modal
  </button>
 
  <!-- Modal -->
  <div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">Modal title</h4>
        </div>
        <div class="modal-body">
          Modal body text goes here.
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
 
</div>
 
<script>
  $('#myModal').on('shown.bs.modal', function () {
    alert('Modal shown!');
  });
</script>
 
</body>
</html>
Conclusion

Modal windows are an important feature of any user-friendly website. By using the 'on' method in jQuery, you can easily attach events to your modal windows to trigger alerts or other code when they are displayed. This helps to make your website more interactive and user-driven.