JS booting correctly, but still will not work if I put it in the console


I have this running after I have output my markup (just before the </body>:

$(document).ready(function() {
    focusLeaving: function(){
                    $('.levelThree').on('mouseleave',function () {
    //This outputs as expect: '#running'

However leaving a .levelThree nothing will happen. If I run the above code inside the console or even run the function itself via the console MM.internalMenu.levelThree.focusLeaving(); the the function works accordingly.

This is confused me no end, I know it should work. I even know its running, so why won't it work....

Using the on function means you are binding an event to a callback handler. $('.levelThree').on('mouseleave',function () { .... } equates to saying "From now on, when a mouseleave event is triggered on the item, do this function".

The function itself will not be executed at that point in time, it will only be set up to execute when a mouseleave event occurs.

To explain further:

<a id="my_link" href="#"> click me! </a>

When you click this, not much happens. Suppose you want it to say You clicked me! when you click on it. You'll need to set it up using the on function.

$("#my_link").on('click', function {
    alert("You clicked me!");

Note that you still haven't seen an alert box with the message. You have only set up the alert box to be shown on a click. If you click the link, only then will you see the alert box.

What's important to note is that setting up an event handler does not trigger the event itself. However, if you run that code in the console, it will be directly executed. That explains why your code is working when run in the console.

I assume the focusLeaving is an event that fires when a mouse leaves the item? In that case, the easiest way to fix this is by removing the on function, as there is already an event firing and executing. You're setting it up twice, which is what causing the issue you're facing.