Home > Blockchain >  With pure JavaScript, hide an element based on swatch active class and data-swatch-option?
With pure JavaScript, hide an element based on swatch active class and data-swatch-option?

Time:07-09

I'm trying to show a file upload button only for one of the swatch options named 'Custom Logo' in the test product page here.

My code below is incomplete because I find it difficult to read the value of the data-swatch-option attribute and to find if the span has a class named swatch--active that indicates that the swatch in question is selected.

<span data-swatch-option="Custom Logo" data-swatch-index="6947439312956-0" data-booster-initd="true" >Custom Logo</span>
  // Show File Upload button only if Custom Logo variant is clicked/active.
  const el = document.querySelectorAll('span');
  window.onload = function() {
    setTimeout(function() {
      console.log(JSON.stringify(input));
      document.getElementById('hulkapps_option_list_6947439312956').style.display = 'none';
      for (var i = 0; i < el.length; i  ) {
        const current = el[i];
        el[i].addEventListener("click", function (e) {
          if(current.dataset.swatchOption == 'Custom Logo'){
            document.getElementById('hulkapps_option_list_6947439312956').style.display = 'block';
          }else{
            document.getElementById('hulkapps_option_list_6947439312956').style.display = 'none';
          }
        });
      }
    }, 2000);
  };

CodePudding user response:

This should work for you

const el =  document.querySelectorAll('.type')
const input = document.getElementsByClassName('uploader')

input[0].style.display = 'none'

for (var i = 0; i < el.length; i  ) {
  const current = el[i]
    el[i].addEventListener("click", function (e) {
    if(current.dataset.swatchOption == 'Custom Logo'){
      input[0].style.display = 'block'
     }else{
      input[0].style.display = 'none'
     }
      
    });
};
span{
border: 1px solid black;
padding: 10px;
}

input{
margin-top: 50px
}
<div >
<span  data-swatch-option="Custom Logo" data-swatch-index="6947439312956-0" data-booster-initd="true">Custom Logo</span>
<span  data-swatch-option="Design 1" data-swatch-index="6947439312956-0" data-booster-initd="true" >Design 1</span>
 <span  data-swatch-option="Design 2" data-swatch-index="6947439312956-0" data-booster-initd="true">Design 2</span>
<span  data-swatch-option="Design 3" data-swatch-index="6947439312956-0" data-booster-initd="true">Design 3</span>
<span  data-swatch-option="Design 4" data-swatch-index="6947439312956-0" data-booster-initd="true">Design 4</span>
<span  data-swatch-option="Design 5" data-swatch-index="6947439312956-0" data-booster-initd="true">Design 5</span>
<span  data-swatch-option="Design 6" data-swatch-index="6947439312956-0" data-booster-initd="true">Design 6</span>
 </div>
 
 <div ><input type="file"></div>

  • Related