I'm building a web chat with sockets, and I recently added href support for urls like so:
this is a test
text measage with link
when the users click this link i want to prompt: Are you sure you want to open this link
but I'm not sure how to go about it
document.querySelectAll("a").[...]but thats highly in inefficient 'cause new messages will be added and this has to be done every time to include all the ``.
Edit:
I'm specifying that:
I do not want to use the browsers default
window.addEventListener("beforeunload"
As you add text to your chat, append it as an element (div?) so you can apply the event listener to the relevant HTMLElement.
newDiv.querySelectorAll("a")...
Better yet, use event delegation for using just 1 event handler for the container element.
var container = document.querySelector(".container")
container.addEventListener('click', function(ev) {
if (ev.target.tagName == "A") {
ev.preventDefault();
var href = ev.target.href
if (confirm("go to " + href + "?")) {
console.log("do window.location = href here");
}
}
});
<div class="container">
something with a <a href="https://example.com">link</a> that is preventDefault-ed
<br> could have been added dynamically.
</div>