Issue
Good day!
I am trying to get a user to pick a color and when they pick a color, I want to change the value to the color they want. I assumed it would be a boostrap feature since this is from bootstrap, but unfortunately, it would have to be modified and customize manually. Is there a way I can change the value when the user picks the color of their choice.
As of now, I have an onChange=alert to notify user of the color they have chosen, but I want to avoid using alerts and have the value change on behind the user input.
I hope I did my best to explain my issue and I hope to learn from this!
Thank you!
<input type="color" class="form-control form-control-color" id="colorPicker" value="#000002" onchange="alert(this.value);" />
Solution
- Don't use unsafe inline on* handlers. JS should be in one place only and that's its respective tag or file. Use Element.addEventListener() instead
- Create a function to handle your color change and place the logic inside of it
- Get the selected color inside your function from the Event
currentTarget.value
// Cache your elements
const elColorPicker = document.querySelector("#colorPicker");
const elColorCode = document.querySelector("#colorCode");
const elBody = document.querySelector("body");
// Change color function
const changeColor = (evt) => {
const selectedColor = evt.currentTarget.value;
elColorCode.value = selectedColor;
elBody.style.backgroundColor = selectedColor;
};
// Add the Event to your input
elColorPicker.addEventListener("input", changeColor);
<input type="color" class="form-control form-control-color" id="colorPicker" value="#000002">
<input readonly type="text" class="form-control form-control-color" id="colorCode" value="#000002">
Answered By - Roko C. Buljan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.