CSS – Button contrasts with background color

// Get the file input element
const fileInput = document.getElementById(“fileInput”);

// Get the output textarea element
const output = document.getElementById(“output”);

// Get the button area element
const buttonArea = document.getElementById(“buttonArea”);

// Add an event listener to the file input element to handle when a file is selected
fileInput.addEventListener(“change”, function() {
// Get the selected file
const file = fileInput.files[0];

// Create a new FileReader object
const reader = new FileReader();

// Set the onload event handler for the FileReader object
reader.onload = function() {
// Parse the file contents using Papa Parse
const parsedData = Papa.parse(reader.result);

// Get the parsed data as an array of rows, starting from the second row
const rows = parsedData.data.slice(1);

// Extract the values from the rows and store them in an array called texts
const texts = rows.map(row => row.map(value => value.trim()));

// Clear the button area
buttonArea.innerHTML = “”;

// Create a button for each text in the array
texts.forEach(text => {
const button = document.createElement(“button”);
button.textContent = text[0];
button.style.backgroundColor = text[2];
button.style.color = getContrastColor(text[2]); // set text color to contrast with background color

// Add an event listener to the button to display the second value in the output textarea when it is clicked
button.addEventListener(“click”, function() {
output.value += text[1]+” “;
});

buttonArea.appendChild(button);
});
};

// Read the file contents as text
reader.readAsText(file);
});

// Function to get the contrast color for a given background color
function getContrastColor(bgColor) {
// Convert the background color to an RGB array
const rgb = hexToRgb(bgColor);

// Calculate the relative luminance of the color
const luminance = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b;

// Return either black or white depending on the luminance value
return luminance > 128 ? “#000000” : “#FFFFFF”;
}

// Function to convert a hex color code to an RGB object
function hexToRgb(hex) {
// Remove the hash symbol if present
hex = hex.replace(“#”, “”);

// Split the hex code into RGB components
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);

// Return an object with the RGB values
return { r, g, b };
}

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top