mshomali
mshomali

Reputation: 654

Make middle item active in materialize carousel

I have a carousel built with materialize css. I want to start carousel from middle item. But carousel to be start from second item. link of carousel: link What can I do? Thanks in Advance!

Upvotes: 0

Views: 981

Answers (1)

LukeSavefrogs
LukeSavefrogs

Reputation: 607

Please next time add a snippet of code to understand better...

Btw... You can use the instance.set(x) to move the carousel to nth slide (as stated in the docs here)

Here is an example (just comment the instance.set(middle_slide); statement to see the difference):

document.addEventListener('DOMContentLoaded', function() {
  //find wich slide is the middle one
  var carousel_items = document.querySelectorAll('.carousel-item').length;
  var middle_slide = Math.round(carousel_items / 2) 
  
  console.log('The slide in the middle is the ' + middle_slide + ' out of ' + carousel_items)
  
  //Carousel initialization
  var options = {};
  var elems = document.querySelectorAll('.carousel');
  var instances = M.Carousel.init(elems, options);
  
  //Set the carousel to show the middle slide first
  var elem = document.querySelector('.carousel');
  var instance = M.Carousel.getInstance(elem);
  instance.set(middle_slide);
})
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<div class="carousel">
  <a class="carousel-item" href="#one!"><img src="https://lorempixel.com/250/250/nature/1"></a>
  <a class="carousel-item" href="#two!"><img src="https://lorempixel.com/250/250/nature/2"></a>
  <a class="carousel-item" href="#three!"><img src="https://lorempixel.com/250/250/nature/3"></a>
  <a class="carousel-item" href="#four!"><img src="https://lorempixel.com/250/250/nature/4"></a>
  <a class="carousel-item" href="#five!"><img src="https://lorempixel.com/250/250/nature/5"></a>
</div>

Here is the codepen if you prefere: https://codepen.io/LukeSavefrogs/pen/WPYOGE?editors=1010

Upvotes: 1

Related Questions