Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dynamically add a slide to an existing Materialize Carousel?

Tags:

materialize

I am able to create a carousel as described here. The carousel appears and works properly.

Later on I would like to add an additional slide:
$(".carousel").append('<a class="carousel-item active" href="#six!"><img src="http://lorempixel.com/250/250/nature/6"></a>');

However, this does not appear to work as the slide does not get added to the carousel.

Is adding slides to an initialized carousel not supported or is this an issue on my end?

like image 717
Pavel Potoplyak Avatar asked Sep 08 '16 19:09

Pavel Potoplyak


2 Answers

Sure it is. I haven't seen any solution in the internet. I believe that there might be a better and smoother solution but this one is mine.

All you need to do is after adding your new items remove the initialized class from already initialized main carousel div and reinitialize it.

//init carousel
var slider = $('.carousel');
slider.carousel();

//add a new item
slider.append('<a class="carousel-item active" href="#three!"><img src="http://lorempixel.com/250/250/nature/3"></a>');

//remove the 'initialized' class which prevents slider from initializing itself again when it's not needed
if (slider.hasClass('initialized')){
    slider.removeClass('initialized')
}

//just reinit the carousel
slider.carousel(); 

full working fiddle: https://jsfiddle.net/8tq4ycm3/

like image 82
Luke Avatar answered Oct 11 '22 11:10

Luke


I had the same problem, but I'm using the slider. (http://materializecss.com/media.html#slider)

To resolve this, it was necessary to clear all items, re-add items with the new one, and then re-bind the slider.

Follow example: https://codepen.io/troits/pen/QvdZov

let itens = [];
function addItem(){  
  $('.slides').empty();
  $('.slider > .indicators').detach();

  itens.push(createItem());

  for(i in itens){
    $('.slides').append(itens[i]);
  }

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

  showItem(i);
}

function showItem(i){
  $('.slider > .indicators > .indicator-item')[i].click();
}
like image 1
Diego Troitiño Avatar answered Oct 11 '22 11:10

Diego Troitiño