I've created a JSfiddle for a horizontal scrolling navigation element: https://jsfiddle.net/sstracy/goe8j3sv/
Visually, it loads on the page just as I want it except for when the establishing active nav item is too far from the left, smaller screens will hide the active link. Once the page loads, I would like the horizontal nav to scroll to the right, until the active item is visible. Otherwise, the functionality is working just as I want it.
For this testing stage, all the links within the nav do not go anywhere but in the final version, they will direct users to different pages, all pages with the same base navigation code. The only difference will be that each page will have a specific body tag Class that will match the ID provided in each nav link.
I know the code isn't the cleanest as I have started working with a mix of JS and jQuery here... so a solution utilizing either is fine.
I have started some code to hopefully get the nav to scroll but it isn't working:
JS Lines 146-158:
// Scroll if selected item is not in view when the page loads but not after or during user interaction.
var ids, matches = document.body.className.match(/(^|\s)hpn-(\d+)(\s|$)/);
if (matches) {
// found the id
ids = matches[0];
var $elem = ids;
var navPosition = $('#pnProductNav').scrollLeft(),
elemPosition = document.getElementById(ids).offset().left;
$("#pnProductNav").animate({scrollLeft: navPosition + elemPosition}, 800);
}
Any help would be greatly appreciated and I am happy to answer any questions to clear anything up, before help is provided!
I guess I was really just over-thinking this one. I finally got it:
// Scroll if selected item is not in view when the page loads but not after or during.
// First, find and get body class name that starts with hpn-
var ids, matches = document.body.className.match(/(^|\s)hpn-(\d+)(\s|$)/);
if (matches) {
// found the id so define it
ids = matches[0];
// Get position of the nav bar and the position of the link with the matching ID
var navPosition = $('#pnProductNav').scrollLeft(),
elemPosition = $('#' + ids).offset().left;
// Add the two together to get your scroll distance and animate
$("#pnProductNav").animate({scrollLeft: navPosition + elemPosition}, 800);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.