Blog>
Snippets

Dynamic Content Modal

Load dynamic content into a modal based on user interaction, through AJAX calls and DOM manipulation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Content Modal</title>
<style>
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}
</style>
</head>
<body>

<!-- Trigger button -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p id="modal-content-text">Some content will go here...</p>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
  // Make an AJAX call to fetch data
  $.ajax({
    url: 'getContent.php', // Replace with your server URL to fetch data
    type: 'GET',
    success: function(data) {
      // Update modal content with fetched data
      $('#modal-content-text').html(data);
      modal.style.display = 'block';
    }
  });
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = 'none';
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = 'none';
  }
}
</script>
</body>
</html>
HTML structure of the dynamic content modal with necessary CSS styling. JavaScript is used to handle the button click to open the modal, perform the AJAX call to load dynamic content, and close the modal when necessary. The jQuery library is included for AJAX and DOM manipulation.