Trying to change the background color of the paragraph element when someone enters a color into the textbox and hits “change color” button.
.On page load, a random number of elements will be generated. Random numbers are 1-5 elements.
Any advice on how to get this going?
If anyone would like to jump on a Google meet call that would be great.
Do you have some code you can show us? Create an example of what you have tried so we can help you as needed, you can use something like Codepen or whatnot.
Are you supposed to use the color that was typed in? If so it can get more complicated than it needs to be. It would be easier to just supply a list of valid colors to choose from (like a select menu).
Ive only started coding for the past 3 weeks, so I dont know much. Here is what I have so far.
const colors = ['green', 'pink', 'gray', 'black', 'red', 'blue', 'indigo', 'violet', 'white', 'yellow'];
const btnColor = document.querySelectorAll('.background-color');
for (let btnColors of colors) {
if (btnColors == colors); {
};
let changeBackground = () => {
console.log('clicked');
}
btnColor.addEventListener('click', changeBackground)
As you can see I am going in every which direction. Ive done hours of searching but either im not understanding (obviously) or nothing is popping out that would be useful.
Get all the buttons using document.querySelectorAll.
Add an event listener to all the buttons.
Inside the button click handler function get the event.target. Using the target you can get to the previousElementSibling and nextElementSibling that is the input element and the paragraph element surrounding the button. Pass the element and color value to a function.
// destructor target off the event object just for ease
const handleColorSubmit = ({ target }) => {
// input element before the button
console.log(target.previousElementSibling)
// input element value
console.log(target.previousElementSibling.value)
// paragraph element after the button
console.log(target.nextElementSibling)
// some function to set the color (input value) on the paragraph element
// paragraph = target.nextElementSibling
// color = target.previousElementSibling.value
handleColorChange(paragraph, color);
}
Using the two arguments paragraph and color set the style attribute on the paragraph element using the color.
For bonus points, check the color was valid by looking at the style attribute on the paragraph element using getAttribute('style'). If it returns null the color that was set was not valid (getAttribute).