Search code examples
javascriptjqueryhtmlbootstrap-slider

Dynamically create javascript plugin elements


I'm trying to dynamically add a bootstrap-slider to my webpage. However, the added slider for some reason isn't getting initialized.

The following jsfiddle demonstrates my problem: https://jsfiddle.net/hLrptave/1/

I have 2 sliders: one currently living on the page (and it works correctly) and one that's dynamically created by javascript when I click a button. The two sliders are exactly the same but the dynamically created one doesn't work (it looks like a regular text input).

The sliders are initialized by jQuery (or javascript) and both have the following code:

<input type="text" class="slider" data-slider-min="0" data-slider-max="10" data-slider-value="5">

So my question is how do I initialize something that doesn't exist on the page yet?

Keep in mind I have lots of these buttons on my webpage. Not sure if that affects anything or not.


Solution

  • Just add

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

    after

    $('#box').append(slider2);
    

    I would advise you to change the classname of the new slider to slider1 beacuse when you create the new one the previous one goes back to middle if they have the same classname

    JSFIDDLE