-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
57 lines (52 loc) · 2.04 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const urlInput = document.getElementById("urlInput");
const addBookmarkButton = document.getElementById("addBookmark");
const deleteAllButton = document.getElementById("deleteAll");
const bookmarkList = document.getElementById("bookmarkList");
function isValidURL(url) {
const pattern = /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?$/;
return pattern.test(url);
}
addBookmarkButton.addEventListener("click", () => {
const url = urlInput.value.trim();
if (isValidURL(url)) {
const bookmarkItem = document.createElement("li");
bookmarkItem.classList.add("bookmark-item");
bookmarkItem.innerHTML = `<a href="${url}" target="_blank">${url}</a>
<div class="buttons">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</div>`;
bookmarkList.appendChild(bookmarkItem);
urlInput.value = "";
addEditBookmarkListener(bookmarkItem);
addDeleteBookmarkListener(bookmarkItem);
}
else {
alert("Please enter a valid URL (http:// or https://).");
}
});
deleteAllButton.addEventListener("click", () => {
while (
bookmarkList.firstChild
) {
bookmarkList.removeChild (bookmarkList.firstChild)
}
});
function addEditBookmarkListener(bookmarkItem) {
const editButton = bookmarkItem.querySelector(".edit");
const bookmarkLink = bookmarkItem.querySelector("a");
editButton.addEventListener("click", () => {
const newURL = prompt("Edit the URL:", bookmarkLink.getAttribute("href"));
if (newURL && isValidURL(newURL)) {
bookmarkLink.setAttribute("href", newURL);
bookmarkLink.innerHTML = newURL;
}
else if (newURL) {
alert("Please enter a valid URL (http:// or https://).");
}
});
}
function addDeleteBookmarkListener(bookmarkItem) {
const deleteButton = bookmarkItem.querySelector(".delete");
deleteButton.addEventListener("click", () => {bookmarkItem.remove();})
}