klmjiub
klmjiub

Reputation: 5

How to change div color from a given value in JavaScript

<div id="nav">
    Some Text
</div>

<input type="text" id="color"><button onClick="changeColor()">Change</button>

<script>

    function changeColor(){

        var colorCode = document.getElementById('color').value;
        var  nav = document.getElementById('nav');

        nav.style.background = "'"+colorCode+"'";
    }

</script>

When i enter for ex.: red in the input field and than press the button, nothing happens.

Upvotes: 0

Views: 567

Answers (6)

Hemanshu Patel
Hemanshu Patel

Reputation: 46

1.please refer to below code which should help you

function changeColor() {
        var colorCode = document.getElementById('color').value;
        var nav = document.getElementById('nav');

        nav.style.background = colorCode;
    }
<div id="nav">
        Some Text
    </div>
    <input type="text" id="color"><button onClick="changeColor()">Change</button>

Upvotes: 1

Kaleemullah
Kaleemullah

Reputation: 544

Below code will work. Sir check.

function changeColor(){

        var colorCode = document.getElementById('color').value;
       document.getElementById("nav").style.color = '#'+colorCode;
    }
<div id="nav">
    Some Text
</div>

<input type="text" id="color" maxlength ="6"><button onClick="changeColor()">Change</button>

Upvotes: 0

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7969

Try this this will work:

function changeColor(){

var colorCode = document.getElementById('color').value;
 $("#nav").css('background', colorCode);
   }

Upvotes: 0

user9575308
user9575308

Reputation:

<div id="nav">
    Some Text
</div>

<input type="text" id="color"><button onClick="changeColor()">Change</button>

<script>

    function changeColor(){

        var colorCode = document.getElementById('color').value;
        var nav = document.getElementById('nav');

        nav.style.backgroundColor = colorCode;
    }

</script>

Upvotes: 0

Bernd Plegt
Bernd Plegt

Reputation: 123

change
nav.style.background = "'"+colorCode+"'";
to
nav.style.background = colorCode;

Upvotes: 0

user11950435
user11950435

Reputation:

You don't need those single quotes, just pass the value itself into the background attribute.

function changeColor(){

        var  nav = document.getElementById('nav');
        nav.style.background = document.querySelector("#color").value;
    }

Upvotes: 1

Related Questions