I have made a div called navarea and inside it I have 6 more div’s. When I mouse over I want to change there background color.
I dont want to have 6 mouse over functions for each div, instead I want to get the names of the divs from an array.
I can change the background colour without the mouseover function in this way, but as soon as I add the mouseover function it does absolutely nothing.
Thank you in advance for you help.
Bill
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var mainnav=["dashboard","sales","marketing","production","accounts","logout"];
jQuery.each(mainnav, function() {
$("#" + this).mouseover(function(){ // Why is this line is failing?
$("#" + this).css("background-color","#8c9aa0");
});
});
});
</script>
<style type="text/css">
#navarea {
height: auto;
width: 180px;
background-color:#FFF;
}
#dashboard {
height: auto;
width: 180px;
background-color:#FFF;
}
</style>
</head>
<body>
<div id="navarea">
<div id="dashboard">Dashboard</div>
<div id="sales">Sales</div>
<div id="marketing">Marketing</div>
<div id="production">Production</div>
<div id="accounts">Accounts</div>
<div id="logout">Logout</div>
</div>
</body>
</html>
You’re using the each function improperly. If the
divs you want to target are within a parent element (for this example, let’s say the parent element ismainnav), then you should just do this:The .hover() function lets you place both the mouseover and mouseout elements in the same function, as you can see above. This minimizes code.
$("#" + this)makes no sense, as$(this)in jQuery selects the active element.I used the
.children()function. All this does is select the elements nested within the selected element, in this case#mainnav.More about
.each()here and more about.children()here.