How to change BGcolor screen using JS function?

I am trying to create a simple button to change the background color using a JS function. can't get it to work though ...

<!doctype html><html>
<head>
<title>Blank Page</title>
    <script type="text/javascript">

        var bg = function(){
            var color = prompt("Please enter a color" , "Color");
            return color;
        }

    </script>
</head>
<body>
<input type="button" value="Change BG" onClick="document.bgColor='bg()'">

</body>
</html>`

      

+3


source to share


4 answers


You need to remove ''

from 'bg()'

. Thus.

Please find document.bgColor has been deprecated since HTML4.0, so it did not recommend using it.



<script>
    function bg(){
    var color = window.prompt("Please pick color");
    return color;
    }
    </script>
    </head>
    <body>
    <input type="button" value="changeBG" onclick="document.bgColor=bg();"/>

    </body>
    </head>

      

+1


source


Wrap your code when the dom is ready:



window.onload=function() {
    var bg = function(){
        var color = prompt("Please enter a color" , "Color");
        return color;
    }
}

      

0


source


Call function without single quotes and color entered in color codes must start with '#'

var color = prompt("Enter the color you want on the Background???");
document.body.style.backgroundColor = color;

      

It will work for you

0


source


Like this:

http://jsfiddle.net/50zj6yxj/

<input type="button" value="Change BG" onclick="change()">

var change = function () {
    var color = prompt("Please enter color", "#000000");
    if (color != null) {
        document.body.style.background = color;
    }
}

      

0


source







All Articles