Search code examples
javascriptjquerydocument-readygetscript

How to set up a $(document).ready function inside a file loaded by $.getScript


I'm trying to compartmentalize the code for a webpage to load code only when needed. I have one javascript file included in the head section of my page. The page has a button, which when clicked, brings a div to the foreground, then populates the div through the use of $.getScript. The newly loaded content consists of two additional divs and ten buttons. However, the buttons don't work. Whether I put the $('#element').click() code on my main html page, in my primary javascript file or the newly loaded file, it doesn't work. Do I have something incorrectly formatted or is this just something that will never work?

$(document).ready(function() {
        alert("Test");  /*     This works     */
        $('#slideButton1').click(function() {
                alert("Testing");     /*   This doesn't     */
        });
});

Buttons are generated by the following code:

function addGalleryButtons() {
        var sLabels = new Array("Aircraft","Avatars","BattleArmor","BattleMechs","Book Covers","Characters","Lego BattleTech","Maps","Naval Vessels","Vehicles");
        var leftIndent = 15;
        for(var i=0; i<sLabels.length; i++) {
                var slBtn = $(document.createElement('div')).attr('id','slideButton'+i);
                slBtn.addClass('base shadowed rad3 gSlideButton');
                slBtn.html(sLabels[i]);
                var slb = { 'left' : leftIndent+'px' , 'opacity' : '0.7' };
                slBtn.css(slb);
                slBtn.attr('title','slideButton'+i);
                slBtn.appendTo('#gallerySlider');
                leftIndent = leftIndent + $('#slideButton'+i).width() + 12;
        }
}

Solution

  • Your problem is that when you bind to $('#slideButton1') it doesn't exist in the DOM. The solution is to bind to the $('#gallerySlider') element using the on method.

    $('#gallerySlider').on( 'click', 'div', function( e ){
      console.log( $( this ), $( this ).attr( 'id' ) );
    });
    

    It might be a good idea to give class names to your divs and target them that way.

    $('#gallerySlider').on( 'click', '.myClassName', function( e ){ // etc