I am a beginner of JS and HTML. I encounter a problem with changing the font color by using addEventListener
here is my part of HTML code
<form> <input type = 'color' class = 'color'> </form>
here is my js code.
// this is for class color const color = document.querySelectorAll('.color'); // I have 2 div block which contains messages. const showTextBox = document.querySelectorAll('.mtext1'); // for each message, they correspond to the different color boxes. color.forEach((element, index) => { element.addEventListener('click', function (e) { console.log(e) showTextBox[index].style.color = color[index].value; }) });
the situation I encounter is when I click the color box, it pops up the Palette, and then you have to “click” again for choosing the color. However, that addEventListener only available for the first click.
What I thought is maybe I can use nested addEventListener? or does javascript has a more efficient way to change color dynamically(or responsively) to solve double click situation?
Advertisement
Answer
you can try this solution. Use input event instead of click.
const color = document.querySelectorAll('.color'); const showTextBox = document.querySelectorAll('.mtext1'); color.forEach((element, index) => { element.addEventListener('input', function (e) { showTextBox[index].style.color = element.value; }) });