replace the native alert with a nicer one in javascript

To replace the native alert with a nicer one, we can create a modal dialog using HTML, CSS, and JavaScript. Here's an example using plain JavaScript and the DOM manipulation:

First, create a modal dialog HTML structure with a message and two buttons, one for confirm and one for cancel:

<div id="modal" class="modal">
  <div class="modal-content">
    <p id="modal-message"></p>
    <button id="modal-confirm">Confirm</button>
    <button id="modal-cancel">Cancel</button>
  </div>
</div>
202 chars
8 lines

Then, add some CSS to style the modal dialog:

.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%;
}

#modal-confirm,
#modal-cancel {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
  margin-right: 5px;
}

#modal-cancel {
  background-color: #f44336;
}
545 chars
36 lines

Finally, add some JavaScript code to replace the native alert with the custom one:

index.tsx
// Get the modal dialog
var modal = document.getElementById('modal');

// Get the message element
var message = document.getElementById('modal-message');

// Get the confirm and cancel buttons
var confirmBtn = document.getElementById('modal-confirm');
var cancelBtn = document.getElementById('modal-cancel');

// Replaces the native alert with a modal dialog
function showAlert(messageText, confirmCallback, cancelCallback) {
  // Set the message text
  message.innerHTML = messageText;

  // Show the modal dialog
  modal.style.display = 'block';

  // Add event listeners to the buttons
  confirmBtn.onclick = function() {
    modal.style.display = 'none';
    if (confirmCallback) {
      confirmCallback();
    }
  };
  cancelBtn.onclick = function() {
    modal.style.display = 'none';
    if (cancelCallback) {
      cancelCallback();
    }
  };
}
854 chars
33 lines

Now, instead of using the native alert, we can call the showAlert function with a message text and callbacks for the confirm and cancel buttons:

index.tsx
showAlert('Are you sure you want to delete this item?', function() {
  // Code to delete the item
}, function() {
  // Code to cancel the delete operation
});
159 chars
6 lines

This will display a custom modal dialog with a message and two buttons, allowing the user to confirm or cancel the operation.

gistlibby LogSnag