Search code examples
javascriptjsonfetch

How to write Javascript in a more effective and shorter way


I have written some code that works for a juxtapose that I have created. Being a beginner at Javascript, I wrote it in ways that it would make sense, and after working on it for a long time I was able to create code that works just fine. However, the code is very repetitive and a lot longer than it should be, though I am unsure as to how to rewrite it without breaking it. I want to make it so that the fetch is only written once, instead of every time it is to be used, plus any other thing that would make the code more compact. Here is the code I wrote:


window.addEventListener("load", (event) => {
   
   const t = "js/test.json"
   fetch(t)
      .then(function (response) {
         return response.json();
      })
      .then(function (jsonObject) {
         var color = jsonObject['color'];
         for (var i = 0; i < color.length; i++) {
            var buttonColor = i;
         if (buttonColor == 0 ) {
            document.querySelector(".btn-1").style.backgroundImage = `url(${color[0].smallImage})`;
         }
         else if (buttonColor == 1 ) {
            document.querySelector(".btn-2").style.backgroundImage = `url(${color[1].smallImage})`;
         } 
         else if (buttonColor == 2 ) {
            document.querySelector(".btn-3").style.backgroundImage = `url(${color[2].smallImage})`;
         } 
         else if (buttonColor == 3 ) {
            document.querySelector(".btn-4").style.backgroundImage = `url(${color[3].smallImage})`;
         }
         else if (buttonColor == 4 ) {
            document.querySelector(".btn-5").style.backgroundImage = `url(${color[0].smallImage})`;
         }
         else if (buttonColor == 5 ) {
            document.querySelector(".btn-6").style.backgroundImage = `url(${color[1].smallImage})`;
         } 
         else if (buttonColor == 6 ) {
            document.querySelector(".btn-7").style.backgroundImage = `url(${color[2].smallImage})`;
         } 
         else if (buttonColor == 7 ) {
            document.querySelector(".btn-8").style.backgroundImage = `url(${color[3].smallImage})`;
         } 
         else if (buttonColor == 8 ) {
            document.querySelector(".btn-9").style.backgroundImage = `url(${color[0].smallImage})`;
         }
         else if (buttonColor == 9 ) {
            document.querySelector(".btn-10").style.backgroundImage = `url(${color[1].smallImage})`;
         } 
         else if (buttonColor == 10 ) {
            document.querySelector(".btn-11").style.backgroundImage = `url(${color[2].smallImage})`;
         } 
         else if (buttonColor == 11 ) {
            document.querySelector(".btn-12").style.backgroundImage = `url(${color[3].smallImage})`;
         } 
         else if (buttonColor == 12 ) {
            document.querySelector(".btn-13").style.backgroundImage = `url(${color[0].smallImage})`;
         } 
         else if (buttonColor == 13 ) {
            document.querySelector(".btn-14").style.backgroundImage = `url(${color[1].smallImage})`;
         } 

         }
      });




   var buttons2 = document.querySelectorAll('.btn');
   for (let i = 0; i < buttons2.length; i++) {
      buttons2[i].onclick = function () {
         let switcher = i;
         if (switcher == 0 ) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "red";
                     document.getElementById("color-title").innerHTML = name;

                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[0].image)
                     {
                        image.src = color[0].image;
                     }
                     else
                     {
                        image.src = color[0].image;
                     }

                  };
               });
         }
         else if (switcher == 1) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "blue";
                     document.getElementById("color-title").innerHTML = name;

                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[1].image)
                     {
                        image.src = color[1].image;
                     }
                     else
                     {
                        image.src = color[1].image;
                     }

                  };
               });
         }
         else if (switcher == 2) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "yellow";
                     document.getElementById("color-title").innerHTML = name;
                     
                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[2].image)
                     {
                         image.src = color[2].image;
                     }
                     else
                     {
                         image.src = color[2].image;
                     }

                  };
               });
         }
         else if (switcher == 3) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "green";
                     document.getElementById("color-title").innerHTML = name;

                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[1].image)
                     {
                        image.src = color[3].image;
                     }
                     else
                     {
                        image.src = color[3].image;
                     }

                  };
               });
         }
         else if (switcher == 4) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "red";
                     document.getElementById("color-title").innerHTML = name;
                     
                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[2].image)
                     {
                         image.src = color[0].image;
                     }
                     else
                     {
                         image.src = color[0].image;
                     }

                  };
               });
         }
         else if (switcher == 5) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "blue";
                     document.getElementById("color-title").innerHTML = name;

                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[1].image)
                     {
                        image.src = color[1].image;
                     }
                     else
                     {
                        image.src = color[1].image;
                     }

                  };
               });
         }
         else if (switcher == 6) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "yellow";
                     document.getElementById("color-title").innerHTML = name;
                     
                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[2].image)
                     {
                         image.src = color[2].image;
                     }
                     else
                     {
                         image.src = color[2].image;
                     }

                  };
               });
         }
         else if (switcher == 7) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "green";
                     document.getElementById("color-title").innerHTML = name;

                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[1].image)
                     {
                        image.src = color[3].image;
                     }
                     else
                     {
                        image.src = color[3].image;
                     }

                  };
               });
         }
         else if (switcher == 8) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "red";
                     document.getElementById("color-title").innerHTML = name;
                     
                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[2].image)
                     {
                         image.src = color[0].image;
                     }
                     else
                     {
                         image.src = color[0].image;
                     }

                  };
               });
         }
         else if (switcher == 9) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "blue";
                     document.getElementById("color-title").innerHTML = name;

                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[1].image)
                     {
                        image.src = color[1].image;
                     }
                     else
                     {
                        image.src = color[1].image;
                     }

                  };
               });
         }
         else if (switcher == 10) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "yellow";
                     document.getElementById("color-title").innerHTML = name;
                     
                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[2].image)
                     {
                         image.src = color[2].image;
                     }
                     else
                     {
                         image.src = color[2].image;
                     }

                  };
               });
         }
         else if (switcher == 11) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "green";
                     document.getElementById("color-title").innerHTML = name;

                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[1].image)
                     {
                        image.src = color[3].image;
                     }
                     else
                     {
                        image.src = color[3].image;
                     }

                  };
               });
         }
         else if (switcher == 12) {
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "red";
                     document.getElementById("color-title").innerHTML = name;
                     
                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[2].image)
                     {
                         image.src = color[0].image;
                     }
                     else
                     {
                         image.src = color[0].image;
                     }

                  };
               });
         }
         else{
            const t = "js/test.json"
            fetch(t)
               .then(function (response) {
                  return response.json();
               })
               .then(function (jsonObject) {
                  const color = jsonObject['color'];
                  for (let i = 0; i < color.length; i++) {

                     let name = "blue";
                     document.getElementById("color-title").innerHTML = name;


                     var image = document.getElementById('bigpic');
                     if (image.getAttribute('src') !== color[3].image)
                     {
                        image.src = color[1].image;
                     }
                     else
                     {
                        image.src = color[1].image;
                     }

                  };
               });
         }
      }
   }
})

Any suggestions?


Solution

    1. ajax call is expansive.if it's a static data, please cache it.
    2. use es6 like a boss if you can.
    3. use function to package same logic.
    4. figure out its model
    5. jquery is good for starter

    give it a try:

    window.addEventListener("load", async (event) => {
      let json = { color: [] } // init data
      try {
        const url = "js/test.json";
        const res = await fetch(url);
        json = response.json();
      } catch (err) {
        // ajax or other err
      }
      const { color } = json; // array
      if (color.length === 0) {
        // no data
        throw new Error('no color data')
      }
      // make color loop between btn?
      const allButtons = document.querySelectorAll('.btn');
      const titleEle = document.getElementById('color-title');
      const imgEle = document.getElementById('bigpic');
      const names = ['red', 'blue', 'yellow', 'green'];
      allButtons.forEach((button, idx) => {
        // idx = 0, btn-1
        // idx = 1, btn-2
        // if not, please change this part
        const offset = idx % color.length; // % => remainder, (idx = 7) % color.length (4?) = 3
        const name = names[offset]
        const { smallImage, image } = color[offset]; // extract smallImage, image
        button.style.backgroundImage = `url(${smallImage})`;
        
        // button.onclick = function?
        button.addEventListener('click', function ($e) {
          titleEle.innerHTML = name;
          imgEle.src = image // no need to check even if no change
          /* you change it anyway, so why are you compare it? this part is waird
          if (image.getAttribute('src') !== color[1].image)
            {
              image.src = color[3].image;
            }
            else
            {
              image.src = color[3].image;
            }
          */
        })
      });
    })