4

So I'm adding list elements to a list using .append(). Within the appended element is a div I need to attach the jQuery Slider widget to. Not sure if I have to use .on() or something. FWIW, an unlimited amount of li's can be added, which is why I'm using a class for the div.

Anyway here's a simplified snippet:

    $('.cycleDuration').slider();

    $cycleBlock += '<li>';
    $cycleBlock += '<div class="cycleDuration"></div>';
    $cycleBlock += '</li>';
    $('#cycles').append($cycleBlock);
Benjamin Allison
  • 2,134
  • 3
  • 30
  • 55

2 Answers2

4

You will need to bind the code before the element is actually appended I think. In this example I just bound a click event because I don't have your slider code.

http://jsfiddle.net/4vwUd/1

$('button').click( function() {
    //turn your div into a jquery object
    var $cycleBlock = $('<div class="cycleDuration"></div>');
    //bind the event
    $cycleBlock.bind('click', function() { alert(); });
    //append to the list
    $('#cycles').append('<li />').children('li:last').append($cycleBlock);
});
mrtsherman
  • 39,342
  • 23
  • 87
  • 111
  • I updated my answer to show how you can make this work for the inner div. It's really just a matter of reordering the operations. – mrtsherman Jan 05 '12 at 04:11
  • Nice. Your comments about efficiency and not re-binding unnecessarily aren't lost on me! – Benjamin Allison Jan 05 '12 at 14:27