Reputation: 29
I am an absolute beginner, and thought that I'd see if i could copy this seemingly basic project (http://jenniferdewalt.com/random_background.html). Rather than just copy the code, I want to figure out why I can't get it to work. I really have no idea how JS interacts with HTML. Here's what i've got:
HTML:
<link type="text/css" rel="stylesheet" href="../../CSS/randomcolor/randomcolour.css" />
<link type="text/javascript" src="../../JS/Random Colour/randomcolour.js">
<script type="text/javascript" src="../../JS/Random Colour/randomcolour.js"></script>
</head>
<body>
<a href="javascript:void(0)" onclick="randomColor()";>
<div .class="button" id="button">
<h2></h2>
</div>
</a>
JS:
function randomColor() {
return '#' + Math.random().toString(16).slice(2, 8);
};
var backgroundColor = randomColor()
This is all probably a million miles off the mark, so if anyone can point me to a resource that will help me out at all, it'd be much appreciated. It's so frustrating not being able to figure this out!
Upvotes: 1
Views: 213
Reputation: 18097
The best way to do this is this.... very easy.
a. first define a function that return random values so less writing.
b. input those into rgba ...
c. you have what you want.
function rand(x){return Math.round(Math.random()*x);}
document.body.style.backgroundColor='rgba('+rand(255)+','+rand(255)+','+rand(255)+','+rand(10)/10+')';
Upvotes: 0
Reputation: 22395
Use this function to generate a random color!
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
And in your html, the period before class
is not needed.
Then, set the body of the page with:
document.body.style.backgroundColor = get_random_color(); //or stick with randomColor();
It's also better practice not to use inline javascript, try setting the onclick event like this (removing it from the html)
var button = document.getElementById("button");
button.onclick = function() {
//set body style here
}
Oh, one more thing: you're trying to use a link
tag to reference a javascript file -- this will not work. That's for CSS!
Upvotes: 3
Reputation: 6992
You are only storing the background color in a temporary variable, you need to store it into the backgroundColor css property of the body
so you need
document.body.style.backgroundColor = randomColor()
where you want to change the background color.
For examlple you could put this directly in the onClick handler, or call function that does this.
Upvotes: 1