I'm a beginner in Javascript.
I made this mock slider that actually uses the ID selection at the click of the arrows and sequentially. As the slides scroll, the menu item is highlighted. You can scroll either with the classic mouse scroll, clicking on the menu items or on the arrows.
I have built the slider on Divi.
You can find the slider here: https://development.nutfordesign.com/product-parallax-scroll/
First of all I would like to understand if it has been realized in the right way, especially the Javascript code.
Also, I can't solve two problems:
- the highlighting of the menu items is not smooth;
- if I scroll the page with the mouse or click the menu items, the position is not updated for the arrows. If I click on the last menu item and then try to go back up by clicking on the up arrow, it doesn't work because, for the arrows, they are still in the initial position.
I hope I have explained myself and I apologize for any beginner's errors.
$(document).ready(function() {
var $currentElement = $(".single-product").first();
$("#down").click(function() {
var $nextElement = $currentElement.next('.single-product');
// Check if the next element exists by measuring its length
if ($nextElement.length) {
// Se esiste, aggiorna l'elemento corrente e scorre
$currentElement = $nextElement;
$('html, body').stop(true).animate({
scrollTop: $nextElement.offset().top
}, 1000);
}
return false;
});
$("#up").click(function() {
var $prevElement = $currentElement.prev('.single-product');
// Check if the next element exists by measuring its length
if ($prevElement.length) {
// Se esiste, aggiorna l'elemento corrente e scorre
$currentElement = $prevElement;
$('html, body').stop(true).animate({
scrollTop: $prevElement.offset().top
}, 1000);
}
return false;
});
//highlight anchor link on scroll
// Cache selectors
var topMenu = $("#product-menu"),
topMenuHeight = topMenu.outerHeight() 100,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function() {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
// Bind to scroll
$(window).scroll(function() {
// Get container scroll position
var fromTop = $(this).scrollTop() topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href='#" id "']").parent().addClass("active");
});
});
CodePudding user response:
