1

I have been working on a project which requires a 3-d carousel, so i decided to take the help of Materialize CSS, but i'm facing an issue of adding any image to it using javascript. I wanted to append an image under the div of class "carousel-item" which is under div of class "carousel" to the following code,

    <div class="carousel" id="grandparent"> 
        <div class="carousel-item"><img src="image1.jpg" name="image-1"></div>
        <div class="carousel-item"><img src="image2.png" name="image-2"></div>
        <div class="carousel-item"><img src="image3.jpg" name="image-3"></div>
        <div class="carousel-item"><img src="image4.jpg" name="image-4"></div>
        <div class="carousel-item"><img src="image5.jpeg" name="image-5"></div>
        <div class="carousel-item"><img src="image6.jpg" name="image-6"></div>
    </div>

This is what i tried,

var divmain=document.getElementById("grandparent");    
var newdiv=document.createElement("div");    
newdiv.className+="carousel-item";   
divmain.appendChild(newdiv);   
var image=document.createElement("img");    
image.setAttribute("src","image7.jpeg");    
image.setAttribute("name","image7");    
newdiv.appendChild(image);

But the above code is just overlapping the image on the top of carousel and even not moving with the carousel slide.

Can anybody help?

1 Answers1

0
  • Make sure you have included materialize javascript and jQuery .
  • jQuery must be above the materialize javascript.

* In materialize you have to intialize crousel by javascript of jQuery

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.carousel');
    var instances = M.Carousel.init(elems, options);
  });

  // Or with jQuery

  $(document).ready(function(){
    $('.carousel').carousel();
  });

* Add new crousel-item and re-initialize it after appending it in grandparent...

 var divmain = document.getElementById("grandparent");
 var newdiv = document.createElement("div");
 newdiv.classList.add('carousel-item');

 var image = document.createElement("img");
 image.src = "https://lorempixel.com/250/250/nature/3";
 image.setAttribute("name","image7");

 newdiv.appendChild(image);

 divmain.appendChild(newdiv);

 // Re intialize crousel
 var elems2 = document.querySelectorAll('.carousel');
 var instances2 = M.Carousel.init(elems2);

I have tried it it is working if not worked for you then tell in the comment...

Anurag Kumar
  • 129
  • 1
  • 7