declaring a variable not on the page yet error
===

So I have this code at the moment:

    $(document).ready(function(){
    $window = $(window),
    $sidebar = $(".sidebar"),
    sidebarTop = $sidebar.position().top,
    sidebarHeight = $sidebar.height(),
    $footer = $(".footer"),
    footerTop = $footer.position().top,    
    $sidebar.addClass('fixed');
    
    $window.scroll(function(event) {
        scrollTop = $window.scrollTop(),
        topPosition = Math.max(0, sidebarTop - scrollTop),
        topPosition = Math.min(topPosition, (footerTop - scrollTop) - sidebarHeight);
        $sidebar.css('top', topPosition);
    });
    });

This is producing an <b>Uncaught TypeError: Cannot read property 'top' of null</b>

I'm still new to jQuery but I'm guessing this is because .sidebar isn't on the page yet, it's a div in an external html file that get injected via AJAX.

I'm thinking I need to change the $(document).ready(function(){ line so it grabs the variable when the .sidebar is actually on the page but I don't really know how to do this. 
I've been playing around with the .on() method but no luck yet.

Any help would be really appreciated!

Thank you!  
