Search code examples
javascripthtmlcssevent-listener

How to change background color when I mention color on input field and hit button


Ok guys I have a simple form and form and it has one input field which has id #input. And I have a button which has the value of add. Now my motive is that when I type any color on input field and click the add button then that color should show on the background of body.


Solution

  • You can do it like this:

    <form>
        <input type="text" id="input">
        <button onclick="document.body.style['background-color'] = document.getElementById('input').value;return false;">add</button>
    </form>

    Achieving the same with event listener:

    document.getElementById("mybutton").addEventListener("click", function(event) {
        document.body.style['background-color'] = document.getElementById('input').value;
        event.stopPropagation();
    });
        <form>
            <input type="text" id="input">
            <button id="mybutton" type="button">add</button>
        </form>