Search code examples
javascripthtmlhoverchildrennav

Trouble with Java Script applying hover state to div


My coworker helped me with this script today, and it works fine in my test sample, but when I try to incorporate it into my site design it doesn't work. The object is to use a div(boxEnd) to skew and round the corners at the end of the menu bar and apply the hover state of the last menu item(menlast). In my sample I only had one 'a' element, but when I added a second, the hover state was applied to the div by both 'a' elements. So I need to fix the current code to utilize the script, and figure out how to only call the script when the last menu item is in hover.

<script>
$(document).ready(function() {
    $('nav').hover(function() {
        $(this).children('a').children('#boxEnd').css('background-color','#ffffff');
    }, function() {
        $(this).children('a').children('#boxEnd').css('background-color','#ff2d0a');
    });
});
</script>

</head>

<body>

<!-- TOP NAV -->

<div id="NAVcontainer">
<div align="center" id="topnav">
  <div align="left" id="logo"><img src="images/mml-3-24-264x102.png"/></div>
  <div align="left" id="menu">
    <nav> 
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#portfolio">Portfolio</a>
    <a id="menlast" href="#contact">Contact
    <div id="boxEnd">&emsp;</div></a>
    </nav>
  </div>
</div>
</div>

Solution

  • When you daisy chain $().children it doesn't grab all the children of all the children. It's only going to get the children of the first child. If this is your actual HTML then you want

    $('nav').hover(function() { $('#boxEnd').css(...); });
    

    There's no need to consider the relationship between nav and #boxEnd. $('#boxEnd') is always going to find the right div.

    This assumes that the code you posted is your attempt to fix your problem, not what you had originally after you added the second 'a'. If that's wrong I'll edit this with more details.