Advertisement
noburudesu

JS Practice

Jun 29th, 2023 (edited)
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.39 KB | None | 0 0
  1. // GIVEN: Create a User constructor
  2. const User = function (name) {
  3. this.name = name;
  4. this.lname = this.name.toLowerCase();
  5. this.uname = this.name.toUpperCase();
  6. this.nav = "#nav-" + this.lname;
  7. this.img = "./images/user-" + name + ".png";
  8. }
  9.  
  10. // TODO: Create object constructors as you see fit
  11. let PostInfo = function (title, content, userDate) {
  12. this.title = title;
  13. this.content = content;
  14. this.userDate = userDate;
  15. this.postNumber = ++postCtr;
  16. this.user = currentUser;
  17. }
  18.  
  19.  
  20.  
  21. // GIVEN: These will store all the posts/messages locally
  22. let posts = [];
  23. let messages = []; // OPTIONAL: Use this if you will implement Messenger
  24. let postCtr = 0;
  25.  
  26. // GIVEN: Do not change the values below
  27. let currentUser = new User("Rachel");
  28. const errorTitle = " Please write a title ";
  29. const errorContent = " Please write a content ";
  30.  
  31. // GIVEN: variables to check against Filter Select (the drop-down box)
  32. let selectNone = "None";
  33. let selectRachel = "Rachel";
  34. let selectJack = "Jack";
  35. let selectAshley = "Ashley";
  36.  
  37. // This event listener is equivalent to JQuery's $(document).ready
  38. document.addEventListener("DOMContentLoaded", function () {
  39. // GIVEN: Do not remove
  40. switchUser(currentUser);
  41. toggleFilter(); // This functionality is already GIVEN
  42.  
  43. // TODO: Set the Create Post's date to the current date
  44. const today = new Date();
  45. // Use the given "formatDate" function present in this file to convert "today" to the correct format
  46. $('#post-date').val(formatDate(today));
  47.  
  48. // .________________________________________________________________________.
  49. // || ||
  50. // || Fill up the element behaviours below, you may change it if necessary ||
  51. // ||______________________________________________________________________||
  52. // ' '
  53.  
  54. // TODO: Complete the functionality when clicking Submit Post
  55. document.querySelector("#submit-post")?.addEventListener("click", function (e) {
  56. e.preventDefault(); // Prevents page refresh
  57.  
  58. let title = $('#post-title').val();
  59. let content = $('#post-body').val();
  60.  
  61. // HINT: Fill up the contents of validateFields() first
  62. if (validateFields(title, content)) {
  63. // HINT: If the number of Posts is ZERO, clear post-container first
  64. if (postCtr == 0) {
  65. $('#post-container').empty();
  66. }
  67.  
  68. // get remaining inputs from the input fields
  69. let userDate = new Date($('#post-date').val());
  70.  
  71. // Create a new post and add it to posts
  72. let newPost = new PostInfo(title, content, userDate);
  73.  
  74. posts.push(newPost);
  75.  
  76. // Refresh the displayed posts
  77. refreshDisplay(posts); // Fill up the contents of refreshDisplay() first
  78.  
  79. // Reset the contents of Create Post
  80. resetCreatePost();
  81. }
  82. });
  83.  
  84. // Called when Sort by Date button is clicked
  85. document.querySelector("div#sort-by-date")?.addEventListener("click", function (e) {
  86. sortByPostDate(); // Fill up the contents of sortByPostDate()
  87. });
  88.  
  89. // Called when Filter button is clicked
  90. document.querySelector("div#filter")?.addEventListener("click", function (e) {
  91. toggleFilter(); // This functionality is already GIVEN
  92. });
  93.  
  94. // Called when Filter Drop-down value is changed
  95. document.querySelector("#select-users")?.addEventListener("change", function (e) {
  96. let selectedValue = this.value;
  97. applyFilter(selectedValue); // Fill up the contents of applyFilter() first
  98. });
  99.  
  100. // Called when Sort by Post Order button is clicked
  101. document.querySelector("div#sort-by-order")?.addEventListener("click", function (e) {
  102. sortByPostOrder(); // Fill up the contents of sortByPostOrder()
  103. });
  104.  
  105. // Called when To Top button is clicked
  106. document.querySelector("div#to-top")?.addEventListener("click", function (e) {
  107. scrollToTop(); // Fill up the contents of scrollToTop() first
  108. });
  109.  
  110. // NOTE: Change the function below if you want to implement Messenger
  111. // Called when Send Message button is clicked
  112. document.querySelector("#send-msg")?.addEventListener("click", function (e) {
  113. e.preventDefault(); // Prevents page refresh
  114. });
  115.  
  116.  
  117. // .__________________________________________________________.
  118. // || ||
  119. // || Fill up the functions below, you may also add your own ||
  120. // ||________________________________________________________||
  121. // ' '
  122.  
  123. // TODO: Complete the validateFields() function below
  124. function validateFields(title, content) {
  125. // HINT: Return 'true' if title and content is NOT empty
  126. // else, use the showError() function to show the proper
  127. // error text. Then, return false
  128. let isValid = true;
  129.  
  130. // If title is invalid, show errorTitle
  131. if (title == '') {
  132. showError(errorTitle);
  133. isValid = false;
  134. }
  135.  
  136. // If content is invalid, show errorContent
  137. if (content == '') {
  138. showError(errorContent);
  139. }
  140.  
  141. // If invalid, return false
  142. // If valid, return true
  143. return isValid;
  144. }
  145.  
  146. // TODO: Complete the sortByPostDate() function below
  147. function sortByPostDate() {
  148. // Sort posts by their Date
  149. let sortedPosts = [];
  150.  
  151. sortedPosts = posts.sort((obj1, obj2) => obj1.userDate - obj2.userDate);
  152.  
  153. // Refresh the displayed posts according to the result of the sorting
  154. // maybe we can use a sort function to sort the post by their date based on latest to oldest
  155.  
  156. refreshDisplay(sortedPosts); // Fill up the contents of refreshDisplay() first
  157. }
  158.  
  159. // TODO: Complete the sortByPostOrder() function below
  160. function sortByPostOrder() {
  161. // let post, number;
  162. // let sortedPosts = [];
  163.  
  164. // HINT: Use splice() for inserting values to an array index
  165.  
  166. // Refresh the displayed posts according to the result of the sorting
  167. refreshDisplay(posts); // Fill up the contents of refreshDisplay() first
  168. }
  169.  
  170. // TODO: Complete the applyFilter() function below
  171. function applyFilter(selectedValue) {
  172. // If, selectedValue is equal to selectNone, show all posts
  173. if (selectedValue == selectNone) {
  174. refreshDisplay(posts);
  175. }
  176.  
  177. // Else, (meaning, if a name filter is selected)
  178. else {
  179.  
  180. let filteredPosts = [];
  181. // For each post in posts, if the post name is equal to selectedValue,
  182. // add it to filteredPosts (filteredPosts.push(post);)
  183. for (var i = 0; i < posts.length; i++) {
  184. if (posts[i].user.name == selectedValue) {
  185. filteredPosts.push(posts[i]);
  186. }
  187. }
  188.  
  189. // Refresh the displayed posts according to the result of filtering
  190. refreshDisplay(filteredPosts); // Fill up the contents of refreshDisplay() first
  191. }
  192.  
  193. }
  194.  
  195. $
  196.  
  197. // TODO: Complete the scrollToTop() function below
  198. function scrollToTop() {
  199. window.scrollTo(0, 0);
  200. }
  201.  
  202. // Refreshes the post-container according to the post contents of displayedPosts
  203. function refreshDisplay(displayedPosts) {
  204. // If displayedPosts is empty, show "▓▒░(°◡°)░▒▓<br>Wow such empty..."
  205. // in the post-container (with a "filler-text" class)
  206. if (displayedPosts.length == 0) {
  207. $('#post-container').empty();
  208. let filler = $('<p></p>').addClass('filler-text');
  209. filler.append('▓▒░(°◡°)░▒▓<br>Wow such empty...');
  210. $('#post-container').append(filler);
  211. }
  212. // Else, add each post inside displayedPosts to post-container
  213. else {
  214. displayPosts(displayedPosts);
  215. }
  216.  
  217. }
  218.  
  219.  
  220. function displayPosts(newPosts) {
  221. // Clear post-container and add each post inside newPosts inside it instead
  222.  
  223. $('#post-container').empty();
  224. for (var i = 0; i < newPosts.length; i++) {
  225. displayPost(newPosts[i]);
  226. }
  227. }
  228.  
  229.  
  230. function displayPost(newPost) {
  231.  
  232. // Create elements/tags
  233. // HINT: You can use document.createElement("tag");
  234.  
  235. // Add classes to your created elements so you don't have to style repeatedly
  236. // HINT: You can use $(element1).addClass("class-name");
  237.  
  238. // Set the proper hierarchy of the created elements
  239. // HINT: $(element1).append(element2); will place element2 within element1
  240.  
  241. // Set the proper content/values to the correct elements/tags
  242. // HINT: You can use $(element2).text("Text to Add"); OR $(imgElement).attr("src", "./images/user.png");
  243.  
  244.  
  245. // Place the outermost element (single-post-main) inside post-container
  246. // $("div#post-container").append(single-post-main);
  247.  
  248. let singlePostMain = $('<div></div>').addClass('single-post-main');
  249. let singlePost = $('<div></div>').addClass('single-post');
  250. let spLeft = $('<div></div>').addClass('sp-left');
  251. let spRight = $('<div></div>').addClass('sp-right');
  252. let spPicture = $('<img>').addClass('sp-picture');
  253.  
  254. let spRightContent = $('<div></div>').addClass('sp-right-content');
  255. let spTitle = $('<div></div>').addClass('sp-title');
  256. let spBody = $('<div></div>').addClass('sp-body');
  257. let spRightBottom = $('<div></div>').addClass('sp-right-bottom');
  258. let spName = $('<div></div>').addClass('sp-name');
  259. let spDate = $('<div></div>').addClass('sp-date');
  260.  
  261. // adding values
  262. spPicture.attr('src', newPost.user.img);
  263. spTitle.text(newPost.postNumber + '. ' + newPost.title);
  264. spBody.text(newPost.content);
  265. spDate.text(formatDateCustom(newPost.userDate));
  266. spName.text(newPost.user.name);
  267.  
  268.  
  269. // appending right side elements
  270. spRight.append(spRightContent);
  271. spRightContent.append(spTitle);
  272. spRightContent.append(spBody);
  273. spRightBottom.append(spName);
  274. spRightBottom.append(spDate);
  275. spRightContent.append(spRightBottom);
  276.  
  277. spLeft.append(spPicture);
  278.  
  279. singlePost.append(spLeft);
  280. singlePost.append(spRight);
  281.  
  282. singlePostMain.append(singlePost);
  283.  
  284. // append to #post-container
  285. $('#post-container').append(singlePostMain);
  286. }
  287.  
  288. // Reset the values of Create Post
  289. function resetCreatePost() {
  290. // Empty the contents of Title and Content
  291. // Set the Date to the current Date today
  292. $('#post-title').val('');
  293. $('#post-body').val('');
  294. $('#post-date').val(formatDate(today));
  295. }
  296.  
  297. /* my function declarations */
  298. function formatDateCustom(userDate) { // GIVEN: For date formatting
  299. let formattedDateCustom = userDate.getFullYear().toString() + '-' + (userDate.getMonth() + 1).toString().padStart(2, 0) + '-' + userDate.getDate().toString().padStart(2, 0) + ' | Time: ' + userDate.getHours().toString().padStart(2, 0) + ':' + userDate.getMinutes().toString().padStart(2, 0);
  300. return formattedDateCustom;
  301. }
  302.  
  303. // ._____________________________________.
  304. // || ||
  305. // || Do not change the functions below ||
  306. // ||___________________________________||
  307. // ' '
  308. function formatDate(today) { // GIVEN: For date formatting
  309. let formattedDate = today.getFullYear().toString() + '-' + (today.getMonth() + 1).toString().padStart(2, 0) + '-' + today.getDate().toString().padStart(2, 0) + 'T' + today.getHours().toString().padStart(2, 0) + ':' + today.getMinutes().toString().padStart(2, 0);
  310. return formattedDate;
  311. }
  312.  
  313. document.querySelector("input#post-title")?.addEventListener("click", function (e) { // GIVEN: For error handling
  314. hideError();
  315. });
  316. document.querySelector("textarea#post-body")?.addEventListener("click", function (e) {
  317. hideError();
  318. });
  319.  
  320. function hideError() {
  321. document.getElementById("post-error").innerHTML = "";
  322. }
  323.  
  324. function showError(errorText) {
  325. document.querySelector("#post-error").innerHTML = "";
  326. document.querySelector("#post-error").innerHTML += " [ERROR] " + "<span>" + errorText + "</span>" + " ! ";
  327. }
  328.  
  329. document.querySelector("#nav-rachel")?.addEventListener("click", function (e) { // GIVEN: For user switching
  330. let user = new User("Rachel");
  331. switchUser(user);
  332. });
  333. document.querySelector("#nav-jack")?.addEventListener("click", function (e) {
  334. let user = new User("Jack");
  335. switchUser(user);
  336. });
  337. document.querySelector("#nav-ashley")?.addEventListener("click", function (e) {
  338. let user = new User("Ashley");
  339. switchUser(user);
  340. });
  341.  
  342. function switchUser(newUser) {
  343. showAllUsers();
  344. document.querySelector("#nav-current-name").textContent = newUser.name;
  345. document.querySelector("#nav-selected").src = newUser.img;
  346. showAllUsers();
  347. document.querySelector(newUser.nav).hidden = true;
  348. currentUser = newUser;
  349. }
  350. function showAllUsers() {
  351. document.querySelector("#nav-rachel").hidden = false;
  352. document.querySelector("#nav-jack").hidden = false;
  353. document.querySelector("#nav-ashley").hidden = false;
  354. }
  355. function toggleFilter() {
  356. const selectUsers = document.getElementById("select-users");
  357. selectUsers.hidden = !selectUsers.hidden;
  358. if (!selectUsers.hidden) {
  359. let selectedFilter = selectUsers.value;
  360. applyFilter(selectedFilter);
  361. }
  362. else {
  363. refreshDisplay(posts);
  364. }
  365. }
  366. });
  367.  
  368.  
  369.  
  370.  
  371.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement