Home > database >  How to change backgroundcolor of HTML element by using input from HTML form using JS EventListener
How to change backgroundcolor of HTML element by using input from HTML form using JS EventListener

Time:10-21

I'm fairly new to JS and i'm having trouble changing the background of a HTML element by using input from a HTML form and event listeners. This is what i've tried so far:

HTML:

<div class="item" id="taskThreeContainer">
<h2>Task 3</h2>
<p>When writing a valid CSS background color in the input below, the background of this item should change to that color.</p>
<input type="text" id="task3Input">
<script src="script.js" async defer></script>

JS:

//Task 3
const inputColor = document.getElementById("task3Input").value;
const taskThreeContainer = document.getElementById("taskThreeContainer");

function convertColor() {
    taskThreeContainer.style.backgroundColor = inputColor;
};

document.getElementById("task3Input").addEventListener("input", convertColor);

Any help would be much appreciated

Solution (JS):

//Task 3
const taskThreeContainer = document.getElementById("taskThreeContainer");

function convertColor() {
    const inputColor = document.getElementById("task3Input").value.toString();
    taskThreeContainer.style.backgroundColor = inputColor;
};

document.getElementById("task3Input").addEventListener("input", convertColor); 

CodePudding user response:

Well, you need to read the value, being actual / valid at the time You want to apply it to style:

<script >
  const inputColor = () => document.getElementById("task3Input").value.toString();
const taskThreeContainer  = () => document.getElementById("taskThreeContainer");

function convertColor() {
 
  console.log(inputColor())
  taskThreeContainer().style.backgroundColor = `${inputColor()}`;
};

document.getElementById("task3Input").addEventListener("blur", convertColor);

</script>

https://plnkr.co/edit/0U8s8a4NUciwTgGt?open=lib/script.js

CodePudding user response:

function getColor() {
  let color = document.forms["colorForm"]["color"].value;
  documen.getElementById("changeable_element").style.color = color;
}
<div id="changable_element">Something...</div>
<form name="colorForm" onsumit="getColor()">
<input type="text" name="color"/>
<input type="submit" name="Submit"/>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You will need to make something like this. It's also recommened to check the input if its a valid color.

  • Related