Search code examples
jquerynouislider

Invoking Jquery NoUISlider on appeneded elements


I'm currently having issues in getting the jquery noUISlider to work on appended elements. I am appending new elements via ajax to my DOM. These elements do not have noUiSlider enabled on them. My code is below. If anybody has solved this problem in the past it would be greatly appreciated:

Here is the code used to originally create the sliders for each item: As you can see I just loop through dom elements tagged with slider and use the libraries native functions with some parameters

$('.slider').each(function()

{

// get prod id
var id = $(this).attr('data-id');

// get max price of product
var max = parseInt($(this).attr('data-max'));

// get current price of product
var current = parseInt($(this).attr('data-current'));

// initiate slider
$(this).noUiSlider({
    start: current,
    step: 1,
    range: {
        'min': 1,
        'max': max,
    },
    connect:'lower'

});     

// link slider to input
$(this).Link('lower').to($('#output-'+id));

// slider event handler
$(this).on({

    // on slider change
    change: function()
    {

        // get product form
        var form = $('#update-'+id);

        // initiate AJAX call
        $.ajax({
            type: form.attr('method'),
            url: form.attr('action'),
            data: form.serialize(),
            dataType: "json",
            success: function(data){

                // update UI
                var ui = $('#product-'+id).find('.status');
                ui.fadeOut(300);
                ui.fadeIn(300);

            }
        });
    }

});

});

});

And here is the code for my appending of elements

 // exectute paginate
  $.ajax({
    url: paginate_link,
    type: "GET",
    dataType: "HTML",
    success: function(data) {

      // generate next page
      var next_page = page + 1;

      // append products
      $('.grid-products').append(data);

      // check if we still have more
      if(next_page <= max_page)
      {

        // increment page counter
        $('.lazy-paginate').attr('data-page', next_page);

      }
      else 
      {

        // hide
        $('.lazy-paginate').addClass('resp-hidden');

      }

    }
})

Now the issue is these appended elements do not have the noUISlider workable on them. I cannot simply run ('slider').noUISlider again because this would reset all of the elements on the page who may have had their values changed. Is there anyway to run the slider function again with the same settings as first time only on new elements.

Any help will be greatly appreciated. Thanks


Solution

  • Managed to solve the issue by wrapping my noSlider initialization in a function which I run upon page load and when I load more products. When I run the .each no slider stuff I simply remove the slider class so upon next load it wont try and do the same DOM elements.