Reena Verma
Reena Verma

Reputation: 1685

Move carousel item in middle of carousel on click (JavaScript)

Struggling with this one... I have a carousel, where when you click on any item, I would like that active item to move, to shift to the center of the carousel.

I have my working code here so far: https://codepen.io/ReenaVerma1981/pen/KKKZoYV#=

(I've mashed 3 scripts into the JS view, so apologies for the long JS code).

As you can see, I can scroll left and right fine.
And I am using getBoundingClientRect(), to calculate element width/heights.

But I'm stuck on where to go from here... Ultimately, if I click on any carousel item, I'd like all the items to shift, so the active item, sits in the middle of carousel.

    const getMostCentered = () => {
  const items = getCarouselContainer().getElementsByTagName('div');
  // Find center of the carousel
  const bounds = calculateItemBounds(getCarouselContainer());
  const center = bounds.left + (bounds.width / 2); 

  for (var i = 0; i < items.length; i++) {
    const current = calculateItemBounds(items[i]);
    const next = calculateItemBounds(items[i+1]);
    // Find the first item whose left edge is past the center 
    if ((next && next.left) > center) {
      if ((next.left - center < center) - current.right) {
        console.log(items[i+1]);
          return items[i+1];
      } 
    } 
  }
}

I found this JSfiddle, but struggling to translate this from jQuery into JavaScript: http://jsfiddle.net/rUZHg/3/

Any help would be amazing...

Upvotes: 0

Views: 1087

Answers (1)

Murali Nepalli
Murali Nepalli

Reputation: 1618

Just change the method getImages as follows. Updated pen https://codepen.io/Code006/pen/RwwQOoq

function getImages(carouselContainer) {
  fetch(`${searchURL}?key=9656065-${apikey}&q=manhattan&image_type=photo&page=1&per_page=9`)
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      console.log('data', data);
      // console.log(type)

      let result = '';
      data.hits.forEach(elem => {
        console.log(typeof elem.largeImageURL);
        result +=
                `<div class="item animated fadeIn slow">
                   <a href="#"><img src="${elem.largeImageURL}" role="presentation" alt="Image of ${elem.tags}"/></a>
                   <p><strong>poster:</strong> <br />${elem.user}</p>
                   <p><strong>tags:</strong> <br />${elem.tags}
                 </div>`;
        carouselContainer.innerHTML = result;
      });

      var carouselItems = carouselContainer.children;
      for (let k=0; k< carouselItems.length; k++) {
        carouselItems[k].setAttribute("index", k);
        //click handler to center the clicked item            
        carouselItems[k].onclick = function(e) {
            let slide = e.currentTarget;
            let slideWidth = slide.getBoundingClientRect().width;
            let slideIndex = parseInt(slide.getAttribute("index"));
            let newLeft = (slideIndex*slideWidth*-1)+Math.floor(((carouselContainer.getBoundingClientRect().width) /slideWidth)/2)*slideWidth;                
            document.getElementById("items-container").style.transition= "all 2s ease 0s";
            document.getElementById("items-container").style.left = newLeft+"px";
        }
      }

      const backGroundImage = data.hits[1].largeImageURL;
      document.getElementById('header').style.backgroundImage = `linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.7)), url(${backGroundImage})`;
      document.getElementById('header').style.backgroundRepeat = 'no-repeat';
    });
}

Upvotes: 1

Related Questions