I have been tasked with creating one long page that will have various small articles for the user to scroll through. Each of the article sections have a category and I need for the URL to reflect that category being viewed. I am aware that history.pushState()
can be used to change a URL when triggered. But it is the logistics that I am unclear about.
I have already figured out a way to have the main menu links jump down to the appropriate category using the following code and it seems to work fine.
$('a.js-link').on('click',function (e) {
e.preventDefault; // dont actually follow the link
var category = $(this).data('category-id'); // get the id we should anchor to
location.hash = '#' + category; // jump to the location hash id
history.pushState("", "", category); // make the url pretty again
return false; // dont append #category to the pretty url
});
However, when a user scrolls down and a new category starts appearing the URL should change to example.com/category2 (as category 1 is the first and will appear on initial page load), user keeps scrolling then URL is changed to example.com/category3. Now if the user scrolls back up it should change back to example.com/category2. Am I simply listening for the scroll event and then checking to see if an element is in the viewport? How do I handle a situation where the upper half of the page is showing a previous category and the lower half the next?
My other roadblock is how to handle linking directly to a specific category on the page. If a user is linked directly to example.com/category5 the page should be loaded and anchored down to the category5 section.
I should mention that I plan on using jquery.lazy.js to load in the main container div's for categories in order to decrease initial page load time. Due to this, I cant use jquery to scroll down to an element since it calculates the size of the element/page and scrolls down by that amount, but then once the content is loaded in it is no longer the appropriate category in view. Although I am open to changing this approach if it majorly affects the ability to change the URL.
Sorry for the wall of text! I am not looking for someone to code this for me, but to push me in the right direction!