Search code examples
javascriptjqueryhtmlbuttoncolor-picker

Change all buttons background-color in javascript


I have here a code which allows me to change the color of the buttons. Weird thing for me is that it only changes one button instead all of them. But I want to have it changed all of them at the same site. Here is a codepen code with HTML: https://codepen.io/akincakiner/pen/EExxMe

/*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(".themecolor");
  var bgColor = document.querySelector(".bgcolor");
  var text = document.querySelector(".onlyTextColor");
  if (side, bgColor, text) {
    side.style.backgroundColor = color;
    bgColor.style.backgroundColor = color;
    text.style.color = color;
  }
}

function updateAll(event) {
  localStorage.setItem('color', event.target.value);
  $(".themecolor, .bgcolor, .onlyTextColor").each(function(index, element){
    if($(element).hasClass("onlyTextColor")){
      $(element).css('color',event.target.value)
    }
    else{
      $(element).css('background-color', event.target.value);
    }
  });
}

Solution

  • If you are using jQuery, just write in jQuery - don't combine with native JS if possible. Otherwise you will confuse your learning of jQuery.

    Demo: http://jsbin.com/zurebutugi/edit?html,js,output

    $(function(){
        var defaultColor = (localStorage.getItem("color")) ? localStorage.getItem("color") : "#0078c0";
    
        function chColor(color){
          $(".themecolor, .bgcolor").css("background-color", color);
          $(".onlyTextColor").css("color", color);
          localStorage.setItem("color", color);
        }
      
        chColor(defaultColor);
      
        $("#theming-color").change(function(){
          chColor($(this).val());
        })
        .val(defaultColor)
        .css("background-color", defaultColor);
    
        
    });