I want to enhance the functionality of a default carousel component by adding custom navigation buttons using JavaScript or jQuery, I don’t understand the carousel’s API or the mechanism it uses for navigation. I’ve looked through the documentation on the component, but couldn’t find anything. Are there predefined methods to control the carousel programmatically? How do you simulate calling the function that moves the carousel forward and back?
AEM Carousel: https://www.aemcomponents.dev/content/core-components-examples/library/core-content/carousel.html
Is there nothing like you use for Bootstrap:
$('#my-next-button').click(function(){ $('#myCarousel').carousel('next'); });
I’ve also posted this in the AEM community = no dice.
2
Answers
I had a similar requirement a few months back and came to the conclusion that the component offers no JavaScript API that would allow it to be tweaked and controlled. That said, I can think of two options you could consider.
Try with data attributes
The README for the Carousel component mentions data attributes recognized by the clientlib associated with the component.
Assuming you have a proxy component for the Carousel (a component within your codebase, which references Carousel V1 as a super type), you could provide your own HTL script, add markup for your additional button, and give it the
data-cmp-hook-carousel="next"
attribute. This is how the built-in buttons workAs far as I can tell by looking at the clientlib, that would only work if you placed those inside the component. That probably wouldn’t make much sense, as such buttons are already present inside the component, so you may as well just use them as-is.
Full customization
For carousels that need to support behaviour significantly different from what’s available out of the box, the way to implement this could be to:
A few words of warning though. Given how flexible AEM can be in terms of where components sit on the page, and how they might interact with one another, you could be facing a lot of edge cases in testing. Whatever solution you propose would probably have to deal with edge cases such as:
In general, writing JavaScript that somehow spans multiple components that can be dragged-and-dropped WYSIWYG style is not to be underestimated in terms of complexity. Identifying and forcing some constraints on what you make possible would definitely help.
I was able to get the AEM core carousel to go to the previous/next slide by clicking the existing button from the javascript. Using your example: