Search code examples
javascriptjqueryhtmlcolor-pickerjscolor

Can't change more then one 1 button color with a color picker


I have here a code that allows me to change the color from elements like a sidebar or buttons with a colorpicker. The data is saved on localstorage.

The weird thing what happening is that this code only allows me to change the color of one of the same item. For example. On a page with 5 buttons. Only one button changes color the other ones stays at their own color. But I want to have all the 5 buttons to be changed

Here is an example i made with the html where you can see that 1 of the 3 buttons just gets a color: https://codepen.io/anon/pen/pLzvNO?editors=1010

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

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

Solution

  • The whole issue is in your updateAll function.

    By using $(this) selector you are selecting your current HTML element.

    According to jQuery Docs

    .each()

    Type: Function( Integer index, Element element )

    A function to execute for each matched element.

    So you can modify your updateAll function to match the following

    function updateAll(event) {
      // Set color to local storage
      localStorage.setItem('color', event.target.value);
      // Loop through elements with 'themecolor' or 'background' classes
      $(".themecolor, .background").each(function(index, element){     
        // If element needs only text color change
        if($(element).hasClass("onlyTextColor")){
          // Change text color
          $(element).css('color',event.target.value)
        }
        // Else
        else{ 
          // Change background color
          $(element).css('background-color', event.target.value);
        }    
      });
    }