0

I'm supposed to create 45 color swatches. I want to be able to use the hex value for the color swatch as well as pass the hex value to a function through an onClick event. How?

Below is my code.

<input class="colBtn c1" id="cp1" type="button" onclick="colChg('#FF6600')" />

function colChg(val) {
  <!-- do something... -->
}

css

.colBtn {
    border: 0.5px outset #000;
    height:15px;
    width:15px;
    cursor:pointer;
    float:center;
}
.c1{
    background-color: #000000;
}

I'want to be able to do something like this:

colVal = array (#ffffff, #cccccc, #ff6600....)
for(i=1;i<45;i++){
<input class="colBtn" id="cp"+i  background-color: colVal[i] type="button" onclick="colChg('colVal[i]')" />
}

}

JonaNathali
  • 177
  • 3
  • 12

2 Answers2

0

You can do it the way you are, but I'd probably do something like:

var colVal = [ 'color1', 'color2', 'color3'], //etc..
    HTMLinsert = ""

colVal.forEach( function( color ) {

     HTMLinsert += '<input class="colBtn c1" id="cp1" type="button" id="' + color +'" />';

});

document.getElementById('insertArea').innerHTML = HTMLinsert;

and then in your handler function:

function colChg(event) {

     color = event.target.id; //this will give you the color
bencripps
  • 2,025
  • 3
  • 19
  • 27
0

loop through the colors array:

colVal = ["#ffffff", "#cccccc", "#ff6600"];
for(var i = 0; i < colVal.length; i++) {
    $("body").append('<button class="colors" style="background-color:' + colVal[i] + ';">click!</button>');
}

to get the color on click:

$(".colors").click(function() {
    var thisColor = $(this).css("background-color");
    alert(thisColor);
});

note: .css("color"); May return RGB value. (see here: RGB to Hex and Hex to RGB)

demo: http://jsfiddle.net/5Q2Wq/2/


UPDATE: little trick to get the color as HEX value without convert:
var thisColorHex = $(this).attr("style").substring($(this).attr("style").indexOf("background-color:") + 17, $(this).attr("style").indexOf(";", $(this).attr("style").indexOf("background-color:"))).trim();

demo: http://jsfiddle.net/5Q2Wq/4/

Community
  • 1
  • 1
meni181818
  • 1,103
  • 1
  • 7
  • 11