-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
80 lines (67 loc) · 2.21 KB
/
script.js
File metadata and controls
80 lines (67 loc) · 2.21 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Getting the elements
let website = document.querySelector("#website");
let url = document.querySelector("#url");
let bookmark = document.querySelector("#bookmark");
let container = document.querySelector(".container");
// --- Load saved bookmarks on page load ---
document.addEventListener("DOMContentLoaded", loadBookmarks);
// Function to add bookmarks
function addBookmark(website, url) {
if (url.value.startsWith("https://") || url.value.startsWith("http://")) {
const bookmarkData = {
name: website.value,
link: url.value
};
createBookmarkElement(bookmarkData);
saveBookmark(bookmarkData);
// Clear inputs
url.value = "";
website.value = "";
} else {
alert("Please enter a valid URL");
url.value = "";
}
}
// Create and insert DOM element for a bookmark
function createBookmarkElement(bookmarkData) {
let container2 = document.createElement("div");
container2.classList.add("container2");
container2.innerHTML = `
<li>
<a href="${bookmarkData.link}" target="_blank">${bookmarkData.name}</a>
<button type="button" class="btn btn-danger">Remove</button>
</li>
`;
container.appendChild(container2);
// Delete handler
let remove = container2.querySelector(".btn-danger");
remove.addEventListener("click", () => {
container2.remove();
removeBookmark(bookmarkData.link);
});
}
// --- LocalStorage Functions ---
function saveBookmark(bookmarkData) {
let bookmarks = JSON.parse(localStorage.getItem("bookmarks")) || [];
bookmarks.push(bookmarkData);
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
function removeBookmark(link) {
let bookmarks = JSON.parse(localStorage.getItem("bookmarks")) || [];
bookmarks = bookmarks.filter(b => b.link !== link);
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
function loadBookmarks() {
let bookmarks = JSON.parse(localStorage.getItem("bookmarks")) || [];
bookmarks.forEach(createBookmarkElement);
}
// --- Event listeners ---
bookmark.addEventListener("click", () => {
addBookmark(website, url);
});
// Pressing Enter also bookmarks the website
document.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
addBookmark(website, url);
}
});