Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- async function attachEvents() {
- const postsRes = await fetch('http://localhost:3030/jsonstore/blog/posts');
- const posts = await postsRes.json();
- const commentsRes = await fetch('http://localhost:3030/jsonstore/blog/comments');
- const comments = await commentsRes.json();
- const btnLoadPosts = document.getElementById('btnLoadPosts');
- const btnViewPost = document.getElementById('btnViewPost');
- const selectMenu = document.getElementById('posts');
- btnLoadPosts.addEventListener('click', loadPostsOptions);
- btnViewPost.addEventListener('click', viewPostDetails);
- function loadPostsOptions() {
- selectMenu.innerHTML = '';
- for (const post in posts) {
- const title = posts[post].title
- const id = post;
- const optionEl = document.createElement('option');
- optionEl.id = id;
- optionEl.textContent = title;
- selectMenu.appendChild(optionEl);
- }
- }
- function viewPostDetails() {
- const selectedIndex = selectMenu.selectedIndex;
- const selectedOption = selectMenu.options[selectedIndex];
- const id = selectedOption.id;
- const title = selectMenu.value;
- const body = posts[id].body;
- document.getElementById('post-title').textContent = title;
- document.getElementById('post-body').textContent = body;
- const commentsUl = document.getElementById('post-comments');
- const commentsArr = Object.values(comments).filter(x => x.postId === id);
- commentsArr.forEach(line => {
- const currentComment = line.text;
- const litElement = document.createElement('li');
- litElement.textContent = currentComment;
- commentsUl.appendChild(litElement);
- })
- }
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment