Search code examples
javascriptjqueryhtmlcsscolor-picker

Change color from more elements then one in Javascript?


Okay, I have this code which allows me to change the sidebar(HTML page) color by any color I want with a color picker. And it saves (localstorage).

The problem is that I can't figure out how to change more elements with the same code. Like now only the sidebar changes color but I also want something like the buttons changing color with the same color picker.

My situation is something like this: https://codepen.io/anon/pen/wyVQbe

/*Set your own color*/
var jscolor;
var defaultColor = (localStorage.getItem("color")) ? localStorage.getItem("color"): "#0078c0";

window.addEventListener("load", startup, false);
function startup() {
  jscolor = document.querySelector(".jscolor");
  if (jscolor) {
    jscolor.value = defaultColor;
    jscolor.addEventListener("input", updateFirst, false);
    jscolor.addEventListener("change", updateAll, false);
    jscolor.select();
  }
  refreshSidebar(defaultColor);
}

function updateFirst(event) {
  refreshSidebar(event.target.value);
}

function refreshSidebar(color) {
  var side = document.querySelector(".sidebar");
  if (side) {
    side.style.backgroundColor = color;
  }
}

function updateAll(event) {
  document.querySelectorAll(".sidebar").forEach(function(side) {
    side.style.backgroundColor = event.target.value
    localStorage.setItem('color', event.target.value);
  });
}

Solution

  • A way (might be or might not be ideal )

    For all the elements you can differentiate like below elements.

    <div class='themecolor onlyTextColor'> hello1</div>
    <div class='themecolor'> hello2</div>
    <div class='themecolor onlyTextColor'> hello3</div>
    <div class='themecolor'> hello4</div>
    <div class='themecolor'> hello5</div>
    

    Where classes with onlyTextColor should update only text color and remaining should update background ( We can have another class like onlyBackground to update only background)

    and use something like below (you have tagged Jquery aswell. So I am using jquery below)

     $('.themecolor').each(function(){
         localStorage.setItem('color', rgba);
        if ($(this).hasClass("onlyTextColor"))
          {
              $(this).css('color', rgba);
          }
        else
          $(this).css('background-color', rgba);
      }) 
    }
    

    Codepen here