Bob Nowak
Bob Nowak

Reputation: 410

How to optimize and minify the following code

I am attaching an excerpt from my code:

  document.getElementById("product-selector-25b").onchange = function () {
    document.getElementById("purchase-25b").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
  }
  document.getElementById("product-selector-26").onchange = function () {
    document.getElementById("purchase-26").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
  }
  document.getElementById("product-selector-29").onchange = function () {
    document.getElementById("purchase-29").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
  }
  document.getElementById("product-selector-Zx3").onchange = function () {
    document.getElementById("purchase-Zx3").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
  }
  document.getElementById("product-selector-001sfF").onchange = function () {
    document.getElementById("purchase-001sfF").href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
  }

As you can see, the code is repeated in everything except IDs getElementById("product-selector-25b") purchase-25b

The problem is that in total I have hundreds of different IDs and I believe that this code can be optimized somehow, but I don’t understand how. What do you advise?

Upvotes: 0

Views: 50

Answers (2)

Prais
Prais

Reputation: 969

My solution is this:

var elements = document.querySelectorAll('[id^="product-selector-"]');

var updateLink = function(el) {
    var tagId = el.id.replace("product-selector-", "");
    document.getElementById("purchase-" + tagId).href = "https://example.com/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}

for (var i=0; i < elements.length; i++) {
    elements[i].addEventListener("change", function(){
      updateLink(this);
    });
}

Note: I assume all IDs start with "product-selector-". Otherwise you need to create an array which contains all the IDs.

Upvotes: 1

Johan
Johan

Reputation: 2962

Here is how you can refacto your code :

const selectors = [
  "product-selector-25b", 
  "product-selector-26", 
  "product-selector-29", 
  "product-selector-Zx3", 
  "product-selector-001sfF"
];

const updateLink = (e) => {
  const selectorId = e.target.id;
  const productId = e.target.selectedOptions[0].getAttribute("data-product");
  const variationId = e.target.value;
  const purchaseId = `purchase-${selectorId.split("-")[1]}`;
  document.getElementById(purchaseId).href = `https://example.com/?add-to-cart=${productId}&variation_id=${variationId}/`;
};

document.addEventListener("DOMContentLoaded", () => {
  selectors.forEach(selectorId => {
    const element = document.getElementById(selectorId);
    if(element){
       element.onchange = updateLink;
    }else {
       console.error(`Element with id ${selectorId} not found`)
    }
  });
});

Just add others ids to the array.

When you want to optimize a repetitive code, the idea is to create a reusable function and loop inside of it

Upvotes: 3

Related Questions