I am in the process of developing a web-based editor similar to Google Docs and need assistance with enabling users to select colors for their text. Currently, I have buttons for bold, italic, and underline functionalities, but I do not know how to implement a color selection feature. Ideally, after highlighting the text in the editable area, users should be able to choose a color from the buttons. Right now, I only have a button for red, but I want to expand this to include multiple colors. What is the best way to achieve this?
Here’s the base code I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Text Color Editor</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<button class="btn-bold" onclick="document.execCommand('bold',false,null);">B</button>
<button class="btn-italic" onclick="document.execCommand('italic',false,null);">I</button>
<button class="btn-underline" onclick="document.execCommand('underline',false,null);">U</button>
<button class="btn-red">Make Text Red</button>
<div class="editable-area" contenteditable="true"></div>
<script>
var boldButton = document.querySelector('.btn-bold');
var italicButton = document.querySelector('.btn-italic');
var underlineButton = document.querySelector('.btn-underline');
boldButton.addEventListener('click', function() {
boldButton.classList.toggle('active');
});
italicButton.addEventListener('click', function() {
italicButton.classList.toggle('active');
});
underlineButton.addEventListener('click', function() {
underlineButton.classList.toggle('active');
});
</script>
</body>
</html>