Skip to content

Commit 519cd2c

Browse files
committed
Change color picker text color depending on background color
1 parent a2c4615 commit 519cd2c

File tree

1 file changed

+21
-0
lines changed
  • Block/Adminhtml/System/Config/Form/Field

1 file changed

+21
-0
lines changed

Block/Adminhtml/System/Config/Form/Field/Color.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,35 @@ protected function _getElementHtml(\Magento\Framework\Data\Form\Element\Abstract
1212
$(document).ready(function () {
1313
var $el = $("#' . $element->getHtmlId() . '");
1414
$el.css("backgroundColor", "'. $value .'");
15+
$el.css("color", getContrastColor("'. $value .'"));
1516
1617
// Attach the color picker
1718
$el.ColorPicker({
1819
color: "'. $value .'",
1920
onChange: function (hsb, hex, rgb) {
2021
$el.css("backgroundColor", "#" + hex).val("#" + hex);
22+
$el.css("color", getContrastColor(hex));
2123
}
2224
});
25+
26+
function getContrastColor(hexcolor) {
27+
var rgb = hexToRgb(hexcolor);
28+
if (rgb) {
29+
var o = Math.round(((parseInt(rgb.r) * 299) + (parseInt(rgb.g) * 587) + (parseInt(rgb.b) * 114)) / 1000);
30+
return (o >= 125) ? "black" : "white";
31+
} else {
32+
return "black";
33+
}
34+
}
35+
36+
function hexToRgb(hex) {
37+
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
38+
return result ? {
39+
r: parseInt(result[1], 16),
40+
g: parseInt(result[2], 16),
41+
b: parseInt(result[3], 16)
42+
} : null;
43+
}
2344
});
2445
});
2546
</script>';

0 commit comments

Comments
 (0)