It’s not so bad. Here’s the code after being run through a linter:
Converting your var statements to be const was much easier than with the other code. A simple slide object contains all of the information that gets changed:
const slide = {
prev: 0,
current: 0,
next: 0,
index: 0
};
with all the code that references them being updated too, of which a part is:
// slideCurrent = slideIndex;
slide.current = slide.index;
// slidePrev = slideIndex - 1;
slide.prev = slide.index - 1;
// slideNext = slideIndex + 1;
slide.next = slide.index + 1;
Here’s a separate fork of the code after its been updated to use const:
On scanning further through the code, several of the comments didn’t seem to serve any great purpose.
// set first slide as the active slide by default
slides[0].classList.add("active");
Comments like that I have removed, and reduced others so that they just explain why something is being done.
In other cases I’ve updated the code so that the comment isn’t needed, such as with the touch support.
const touchsupport =
"ontouchstart" in window ||
navigator.maxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0;
if (touchsupport) {
// browser supports touch
document.documentElement.className += " has-touch";
}
I have instead renamed the variable so that it more clearly expresses what the comment was saying.
const browserSupportsTouch =
"ontouchstart" in window ||
navigator.maxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0;
if (browserSupportsTouch) {
document.documentElement.className += " has-touch";
}
In the init function though, I did move the section setting the last item offset to the end of the function, so that the other parts above it make better sense as a group.
Another comment section with the events helps to inspire another improvement:
// add event handlers to buttons
next.addEventListener("click", function nextSlide() {
//...
});
prev.addEventListener("click", function prevSlide() {
//...
});
By extracting the nextSlide and prevSlide functions, we can group the event listeners together so that it’s much easier to tell that they are assigning events, without needing the comment to tell us.
next.addEventListener("click", nextSlide);
prev.addEventListener("click", prevSlide);
The comment about putting the code at the end of the body I’ve moved to the top of the code, as it’s much more likely that people will see it there, and the CSS custom variables I’ve grouped together under a separate comment for both of them.
// CSS custom variables
const cssSliderSpeedProperty = "--slider-speed";
const cssSliderSpeedValue = "0.5s";
I also removed commented out code from the nextSlide event handler. That’s about all that I’ve tweaked though, the final results being found in the following forked codePen: