I am working on a small practice program where I have 3 white boxes in a row. My goal is (using Javascript) for any of the boxes to change from white to red when the mouse is over the box, and then to turn yellow when the mouse comes off the box. The code below works on the initial box but not on the other two. When I put the mouse over the other boxes, it doesn't change them but it does change the color on the inital box. I've looked at similar questions but most of them involve jquery, which I am not using. I've done some research and possible solutions might involve using addEventListener or using "this". I don't want to give different names to the button id's and write additional procedures based on them -- that would be inefficient. I know there must be a more efficient way. Any advice is appreciated.
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Whiteboxes 5</title>
<script type="text/javascript">
function changeColorOnMouseOver()
{
var control=document.getElementById("btn");
control.style.background='red';
}
function changeColorOnMouseOut()
{
var control=document.getElementById("btn");
control.style.background='yellow';
}
</script>
<link rel="stylesheet" href="css/app5.css">
</head>
<body>
<input type="button" value="" id="btn"
onmouseover="changeColorOnMouseOver()"
onmouseout="changeColorOnMouseOut()"/>
<input type="button" value="" id="btn"
onmouseover="changeColorOnMouseOver()"
onmouseout="changeColorOnMouseOut()"/>
<input type="button" value="" id="btn"
onmouseover="changeColorOnMouseOver()"
onmouseout="changeColorOnMouseOut()"/>
</body>
</html>
You can use the
this
reference like so:In html ID's should be unique. No 2 elements should have the same ID.
this
will refer to the caller element.