views:

25

answers:

0
$(document).ready(function(){
    var randomId = "id_"+Math.floor(Math.random()*1000);
    var wrap1 = $(document.createElement('div')).css('overflow', 'auto')
        .width(50).height(30).css('border','1px solid black').text('a')
        .attr('id',randomId);

    var content1 = $(document.createElement('div')).width(100)
        .text("The quick brown fox jumped over the lazy dog.");

    var wrap2 = $(document.createElement('div')).css('overflow', 'auto')
        .width(50).height(30).css('border','1px solid black').text('b');

    var content2 = $(document.createElement('div')).width(100)
        .text("Bright vixens jump; dozy fowl quack.");

    var scrollListener = function() {
        wrap1.scrollLeft($(this).scrollLeft());

        //STUPID_ID_TRICK
        //$("#"+randomId).scrollLeft($(this).scrollLeft());
    };    
    wrap2.bind('scroll', scrollListener);

    //This does NOT work
    //Unless I do STUPID_ID_TRICK
    $('body').append(content1);
    $('body').append(content2);

    content1.wrap(wrap1);
    content2.wrap(wrap2);

    //But if I used this instead it would work
    //wrap1.append(content1);
    //wrap2.append(content2);
    //$('body').append(wrap1);
    //$('body').append(wrap2);

});

I am really confused on the above code, the way the code currently is with the wrap()'s it does not work. If instead you comment out the wrap section and uncomment the append section it works exactly as expected.

The only way I can get the wrapping to work is if I do a dumb hack and add a random ID to the wrapper and then use that ID to do a selection, but that seems hacky and really inefficient. Am I doing something fundamentally wrong?

To answer the question "well why not just use append?", I really want to use wrap because the thing I am wrapping is not dynamically generated as it is in my example.