-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathfavorite_quotes.js
More file actions
48 lines (46 loc) · 1.47 KB
/
favorite_quotes.js
File metadata and controls
48 lines (46 loc) · 1.47 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
// Adding event listeners
let hearts = Array.from(document.getElementsByClassName("heart"));
hearts.forEach((heart) => {
if (heart) {
heart.addEventListener("click", on_heart_click);
}
});
/**
* @summary This function is a handler for the event of heart-click.
* Whenever a user clicks on a heart icon, in case of empty heart:
* saves quote in favorites, as well as changing
* the heart icon from empty to full.
* In case of full heart:
* Removes it and switch back to empty heart icon.
* Uses the save_or_remove_quote function to handle db operations.
*/
function on_heart_click() {
const quote = this.parentNode.previousElementSibling.innerHTML.replaceAll(
'"',
""
);
const author_element = this.parentNode;
const author = author_element.innerHTML.split("\\ ")[1].split("\n")[0];
if (this.src.split("/").pop() == "empty_heart.png") {
this.src = "../media/full_heart.png";
save_or_remove_quote(1, quote, true);
} else {
this.src = "../media/empty_heart.png";
save_or_remove_quote(1, quote, false);
if (this.classList.contains("favorites")) {
this.parentNode.parentNode.remove();
}
}
}
/**
* @summary Saves or removes a quote from favorites.
*/
function save_or_remove_quote(user_id, quote, to_save) {
method = to_save ? "post": "delete";
let xhr = new XMLHttpRequest();
xhr.open(method, "/");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(
`user_id=${user_id}"e=${quote}`
);
}