|
| 1 | + |
| 2 | +const getLoremIpsum = numberOfParagraphs => { |
| 3 | + fetch(`https://baconipsum.com/api/?type=meat-and-filler¶s=${numberOfParagraphs}`) |
| 4 | + .then(response => response.json()) |
| 5 | + .then(loremIpsumTextArray => { |
| 6 | + updateResult(loremIpsumTextArray); |
| 7 | + }) |
| 8 | + .catch(error => { |
| 9 | + showError(error); |
| 10 | + }); |
| 11 | +}; |
| 12 | + |
| 13 | +const updateResult = textArray => { |
| 14 | + const resultElement = document.getElementById('result'); |
| 15 | + resultElement.innerHTML = ''; |
| 16 | + resultElement.innerHTML = textArray |
| 17 | + .map(paragraph => `<p>${paragraph}</p>`) |
| 18 | + .join(''); |
| 19 | + addCopyButton(textArray.join('')); |
| 20 | +}; |
| 21 | + |
| 22 | +const showError = error => { |
| 23 | + const resultElement = document.getElementById('result'); |
| 24 | + resultElement.innerHTML = ''; |
| 25 | + resultElement.innerHTML = `<p class="error">${error.message}</p>` |
| 26 | +} |
| 27 | + |
| 28 | +const addCopyButton = text => { |
| 29 | + const resultElement = document.getElementById('result'); |
| 30 | + const copyBtn = document.createElement('button'); |
| 31 | + |
| 32 | + copyBtn.textContent = 'Copy'; |
| 33 | + copyBtn.classList.add('copy'); |
| 34 | + copyBtn.onclick = () => { |
| 35 | + navigator.clipboard.writeText(text); |
| 36 | + copyBtn.textContent = 'Copied!'; |
| 37 | + setTimeout(() => { |
| 38 | + copyBtn.textContent = 'Copy'; |
| 39 | + }, 2000); |
| 40 | + } |
| 41 | + |
| 42 | + resultElement.appendChild(copyBtn); |
| 43 | +} |
| 44 | + |
| 45 | +const getLoremIpsumElement = document.getElementById('getLoremIpsum'); |
| 46 | +const paragraphsCountElement = document.getElementById('paragraphsCount'); |
| 47 | + |
| 48 | +getLoremIpsumElement.addEventListener('click', () => { |
| 49 | + getLoremIpsum(parseInt(paragraphsCountElement.value)); |
| 50 | + paragraphsCountElement.value = ''; |
| 51 | + |
| 52 | +}) |
0 commit comments