Issue
I seem to be getting a script error that mentions both bootstrap alert and my own close alert tag. I have a script that closes alerts after 2.5s when a script is created. It is tied to user actions, for example if a user creates a blog post or deletes a comment, an alert shows with the User task and then auto closes the tag. I seem to be getting a Uncaught TypeError in console and can't figure out why. I can only speculate that it's because it's looking for a alerts msg that isn't there yet?
script.js
// // Event listener for auto close message function using DOM Content Loaded
// // Javascript function for auto close messages
// document.addEventListener("DOMContentLoaded", alertTimeout);
document.addEventListener("DOMContentLoaded", (alertTimeoutalertTimeout) => {
setTimeout(function () {
let messages = document.getElementById("msg");
let alert = new bootstrap.Alert(messages);
alert.close();
}, 2500);
});
index.html bootstrap script
<!-- Bootstrap Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
</html>
Uncaught TypeError: Cannot read properties of null (reading 'defaultPrevented')
at Q.close (alert.js:38:60)
at script.js:11:11
close @ alert.js:38
(anonymous) @ script.js:11
setTimeout (async)
(anonymous) @ script.js:7
Alert.js
Seems to be the EVENT_CLOSE that is showing as error
// Public
close() {
const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE)
if (closeEvent.defaultPrevented) {
return
}
this._element.classList.remove(CLASS_NAME_SHOW)
const isAnimated = this._element.classList.contains(CLASS_NAME_FADE)
this._queueCallback(() => this._destroyElement(), this._element, isAnimated)
}
I have tried to add a document ready to the script and have tried different ways to write and load the script but seems to be the same outcome as always. I have also tried using a older version of bootstrap js link and that works so no console error but then my modal and navbar collapse stopped working so I have to have correct version of the script.
Solution
Use below code..
document.addEventListener("DOMContentLoaded", (alertTimeoutalertTimeout) => {
setTimeout(function () {
$("#msg").alert("close");
}, 2500);
});
Answered By - Pycm
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.