在Magento菜单上自定义javascript

I'm trying to add a custom java-script file into Magento by placing the following into local.xml

<action method="addJs"><script>nav/navigation.js</script></action>

navigation.js

$sub = $('div.col-md-2.right-content');
$('div.col-md-10').on({
    mouseenter: function() {
        var i = $(this).index();
        $sub.addClass('li-'+i);
    }, mouseleave: function() {
        $sub.removeClass().addClass('col-md-2.right-content');

    }
})

style.css

li.level2.nav-2-1-1.first{
    background-color: green;
    }
li.level2.nav-2-1-2.last{
    background-color: red;
    }

The purpose of this is that whenever a user hover over a link inside my submenu, the right-content will change accordingly. The problem is that my navigation.js file is targeting objects that does not exist until after the menu is loaded. These being 'div.col-md-2.right-content' and 'div.col-md-10'.

Is there a way to load the javascript after the menu has loaded? Or is there another way to accomplish this? Or am I just approaching this completely wrong.

You can use the $(function() { ... } ) syntax to have that code run only after all of your DOM is loaded:

$(function() {
    $sub = $('div.col-md-2.right-content');
    $('div.col-md-10').on({
        mouseenter: function() {
            var i = $(this).index();
            $sub.addClass('li-'+i);
        }, mouseleave: function() {
            $sub.removeClass().addClass('col-md-2.right-content');
        }
    })
})

Note that this will work only if the menu is part of your original DOM (part of the HTML code) and not created dynamically.

In case the menu is generated dynamically you can use:

$('body').on('mouseenter', 'div.col-md-10', function() { ... });

Here is a working example:

$(function() {
                    
  $sub = $('.subject');
  $('body')
  .on('mouseenter', '.yeah', function() {
    var i = $(this).index();
    $sub.addClass('li-'+i);
  })
  .on('mouseleave', '.yeah', function() {
    $sub.removeClass().addClass('subject');
  })
  
  $('.test').append($('  <ul>    <li class="yeah"><a href="#">Link 1</a></li>     <li class="yeah"><a href="#">Link 1</a></li>     <li class="yeah"><a href="#">Link 1</a></li>   </ul>'));
  
});
.li-0{
  background-color:green;
}

.li-1{
  background-color:red;
}

.li-2{
  background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">

</div>

<div class="subject">
  <p>hello</p>
</div>

</div>

I think the problem is within the routing in local.xml

<default>
    <reference name="head">
         <action method="addItem">
            <type>skin_js</type><name>js/navigation.js</name><params/>
        </action>        
    </reference>
</default>

Where the navigation.js is in: Note (developer/template) is your template within the skin folder

 site.com/skin/frontend/developer/template/js/navigation.js

The default Tag means that it will be loaded thru the entire site.