Reputation: 13
So, I'm building myself a webpage which will need to contain multiple carousels. I've been successful in creating the first carousel, but haven't been able to crack creating any others.
I've been following Christian Heilmann's Javascript carousel guide and all was going well until I tried to place 2 carousels on the same page.
As the js is affecting classes I assumed that the existing js would affect the copies too. Here's how the working carousel looks and here is how the broken carousel looks.
Any advice about the best way to go about this would be great, I'd love to keep it in vanilla js if possible. Thanks for your help!
And here's the updated js:
carousel = function(id) {
var box = document.querySelector(id + ' .project-pictures');
var next = box.querySelector(id + ' .next');
var prev = box.querySelector(id + ' .prev');
var items = box.querySelectorAll(id + ' .content li');
var counter = 0;
var amount = items.length;
var current = items[0];
box.classList.add('active');
function navigate(direction) {
current.classList.remove('current');
counter = counter + direction;
if (direction === -1 &&
counter < 0) {
counter = amount - 1;
}
if (direction === 1 &&
!items[counter]) {
counter = 0;
}
current = items[counter];
current.classList.add('current');
}
next.addEventListener('click', function(ev) {
navigate(1);
});
prev.addEventListener('click', function(ev) {
navigate(-1);
});
navigate(0);
}();
carouselA = carousel('#carousel-a');
carouselB = carousel('#carousel-b');
note: The div being affected is .project-pictures.
Thanks for your response! Im still not getting the carousel to work - it appears the same in the not working screenshot above, I feel I'm missing something pretty basic here, here's the html for reference and I've updated the js above to reflect your advice:
<div id="carousel-a">
<div class="project-pictures">
<ol class="content">
<li><img src="images/portfolio_img/design_museum/cropped/1.png">
</li>
</ol>
<div class="buttons">
<button class="prev">
</button>
<button class="next">
<span class="offscreen">Next</span> ▶
</button>
</div>
</div></div>
Upvotes: 0
Views: 1658
Reputation: 6784
You are on the right track saying that the javascript affecting css class which applied to both carousels.
What you need to do is to differentiate between the two carousels. One way to do it is to create a unique id for each carousel.
For example
carousel = function(id) {
var box = document.querySelector(id + ' .project-pictures');
var next = box.querySelector(id + ' .next');
var prev = box.querySelector(id + ' .prev');
var items = box.querySelectorAll(id + ' .content li');
// ...
};
carouselA = carousel('#carousel-a');
carouselB = carousel('#carousel-b');
And in your HTML code, insert the appropriate ID for the two carousel elements.
Upvotes: 1