Rothamsted-Ecoinformatics / eRA

e-RA website code
3 stars 0 forks source link

navigation: add proper # when move to tab (enable properbookmarking) #76

Closed nathcast closed 10 months ago

nathcast commented 3 years ago

When a tab is clickon on, the URL stays the same. We might want to change the URL so that people can bookmakr the page opened at the relevant tab (or send links at that tab) Will be useful for twitter and teh like too At the same time, solve issue #6 (highlighting of the tabs properly)

nathcast commented 2 years ago

https://stackoverflow.com/questions/136458/change-the-url-in-the-browser-without-loading-the-new-page-using-javascript

The basic idea is to set the window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don't support onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval for example) and update the page. You will also need to check the hash value on page load to set up the initial content.

If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.

One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.

Share

nathcast commented 2 years ago

Found that page: https://webdesign.tutsplus.com/tutorials/how-to-add-deep-linking-to-the-bootstrap-4-tabs-component--cms-31180 that solves most of our issues quite neatly. Only thing, is that the tab does not get highlighted!

nathcast commented 2 years ago

$(document).ready(() => { let url = location.href.replace(/\/$/, "");

if (location.hash) { const hash = url.split("#"); $('#myTab a[href="#'+hash[1]+'"]').tab("show"); url = location.href.replace(/\/#/, "#"); history.replaceState(null, null, url); setTimeout(() => { $(window).scrollTop(0); }, 400); }

$('a[data-toggle="tab"]').on("click", function() { let newUrl; const hash = $(this).attr("href"); if(hash == "#home") { newUrl = url.split("#")[0]; } else { newUrl = url.split("#")[0] + hash; } newUrl += "/"; history.replaceState(null, null, newUrl); }); });

nathcast commented 2 years ago

But the tab is still set to inactive.