Advertisement
GeorgiLukanov87

Accordions

Feb 28th, 2023
680
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function solution() {
  2.  
  3.     const main = document.getElementById('main');
  4.     const url = `http://localhost:3030/jsonstore/advanced/articles/list`;
  5.     const response = await fetch(url);
  6.     const data = await response.json();
  7.  
  8.     data.forEach(a =>{
  9.        let divAccordion = createElement('div','',['class','accordion']);
  10.        let divHead = createElement('div','',['class','head']);
  11.        let span = createElement('span',a.title);
  12.        let button = createElement('button','More',['class','button','id',a._id])
  13.  
  14.        let divExtra = createElement('div','',['class','extra']);
  15.        let p = createElement('p')
  16.  
  17.        button.addEventListener('click',toggle);
  18.  
  19.        divExtra.appendChild(p);
  20.        divAccordion.appendChild(divExtra)
  21.        divHead.appendChild(button);
  22.        divHead.appendChild(span);
  23.        divAccordion.appendChild(divHead)
  24.        main.appendChild(divAccordion);
  25.     });
  26.  
  27.     async function toggle(ev){
  28.         const accordion = ev.target.parentNode.parentNode;
  29.  
  30.         const p = ev.target.parentNode.parentNode.children[0].children[0];
  31.  
  32.         const extra =ev.target.parentNode.parentNode.children[0]
  33.         console.log(extra)
  34.  
  35.         const id = ev.target.id;
  36.         const url = `http://localhost:3030/jsonstore/advanced/articles/details/${id}`;
  37.  
  38.         const response = await fetch(url);
  39.         const data = await response.json();
  40.  
  41.         p.textContent = data.content;
  42.  
  43.         const hidden = ev.target.textContent === 'More';
  44.  
  45.         extra.style.display = hidden ? 'block':'none';
  46.         ev.target.textContent = hidden ? 'Less':'More';
  47.  
  48.     }
  49.  
  50.  
  51.     function createElement(type, content, attributes = []){
  52.  
  53.         const element = document.createElement(type);
  54.  
  55.         if(content){
  56.             element.textContent = content;
  57.         }
  58.  
  59.         if(attributes.length > 0){
  60.             for(let i = 0;i<attributes.length;i+=2){
  61.                 element.setAttribute(attributes[i],attributes[i+1])
  62.             }
  63.  
  64.         }
  65.         return element;
  66.  
  67.     }
  68.  
  69. }
  70. solution()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement