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);

2 Answers 2

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

This almost works! I just need to hook it up to the div inside the <li>. :)
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.
Nice. Your comments about efficiency and not re-binding unnecessarily aren't lost on me!
2

simply u can re-call " $('.cycleDuration').slider(); " after every appends the list elements, that will bound added class elements to that function.

5 Comments

This is what I was initially thinking, but live only binds to events. slider is not an event and so will never be bound. What he really needs to do is bind it either before or after the element is added. Please note that live has been deprecated by on and delegate. If you are in jQuery 1.4.2+ you shouldn't be using live anymore.
Wow. I could have sworn I tried that... works well, and it's as simple as possible! Thanks.
@BenjaminAllison - I actually wouldn't do it this way. You are rebinding every time to every list element. This has several problems. Foremost is that you are rebinding multiple times. For example the slider handler could fire ten times if you added ten list items. Second, its very inefficient, especially if there are a lot of sliders.
if u append all the 10 elements once then the function will call / rebind only once not ten times.
@BhaveshGangani - that is true. OP didn't specify, but it is a very important aspect of a good answer so it should be clarified to OP. Here is an example. Add a few list items with the button and then click in the first one. jsfiddle.net/4vwUd/4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.