Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. // find elements
  2. var banner = $("#banner-message")
  3. var button = $("button")
  4. const fetchPostsURL = 'https://jsonplaceholder.typicode.com/posts';
  5. const fetchPostURLWithFail = 'https://httpbin.org/get';
  6.  
  7. // handle click and add class
  8. button.on("click", function(){
  9. banner.addClass("alt")
  10.  
  11. // Promises
  12. fetch(fetchPostURLWithFail, {
  13. method: "POST",
  14. })
  15. .then((response) => {
  16.  
  17. if(response.status >= 400) {
  18. throw response.statusText;
  19. }
  20.  
  21. response.json()
  22. .then((posts) => {
  23. const totalPosts = posts.length;
  24. document.querySelector('#display').innerText = `${totalPosts} posts`;
  25. })
  26. .catch((e) => {
  27. const error = e.toString();
  28. document.querySelector('#display').innerText = `error: ${error}`;
  29. });
  30. })
  31. .catch((e) => {
  32. const error = e.toString();
  33. document.querySelector('#display').innerText = `error: ${error}`;
  34. });
  35. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement