Reputation: 7
<!DOCTYPE html>
<html>
<head>
<title>Button Homework</title>
<script>
function first() {
document.getElementById('type1').style.position = 'absolute';
document.getElementById('type1').style.left= "100px";
document.getElementById('type1').style.top= "200px";
var red = Math.floor(Math.random() * 256);
var green = Math.floor(Math.random() * 256);
var blue = Math.floor(Math.random() * 256);
var newColor = "rgb("+ red + "," + green + "," + blue +")";
}
function second() {
document.getElementById('type1').style.position = 'absolute';
document.getElementById('type1').style.left= "0px";
document.getElementById('type1').style.top= "80px";
}
</script>
</head>
<body>
<h1>Special Button</h1>
<input id = 'type1' type = 'button' value = 'Click' onclick = 'output();'
onmouseover= 'first()' onmouseout= 'second()';' />
</body>
</html>
I'm trying to get the button to change to random colors every time you hover over it but I can't seem to get it to work, If anybody knows how, please help me out. Thanks!
Upvotes: 0
Views: 599
Reputation: 1073
If you want your homework to look like you copied it from the internet:
<!DOCTYPE html>
<head>
<title>Button Homework</title>
<style>
#type1{
position: absolute;}
#type1.mouseover{
left: 100px;
top: 200px;}
#type1:not(.mouseover){
left: 0px;
top: 80px;}
</style>
</head>
<body>
<h1>Special Button</h1>
<input id="type1" onclick="Output()" onmouseover="MouseOver(this)" onmouseout="MouseOut(this)" type="button" value="click">
<script>
function MouseOver(button) {
button.classList.add('mouseover');
//set backgroundColor to random hex string
button.style.backgroundColor = '#' + Math.floor(Math.random()*16777215).toString(16);
}
function MouseOut(button) {
button.classList.remove('mouseover');
}
function Output() {
//whatever this does
}
</script>
</body>
</html>
Note that moving the buttons location triggers a mouseout event, so it gets pretty crazy. <style>
doesn't seem to apply when you put it inline in the snippet.
Upvotes: 0
Reputation: 150
All you need to do is assign the color to a style property. In this case the background color of the button.
function first() {
var red = Math.floor(Math.random() * 256);
var green = Math.floor(Math.random() * 256);
var blue = Math.floor(Math.random() * 256);
var newColor = "rgb(" + red + "," + green + "," + blue + ")";
document.getElementById("type1").style.backgroundColor = newColor;
}
Upvotes: 1