If I understand correctly, the issue with your function lies in its handling of the random
link. This link has an href
value like http://mysite.com/random
, but when clicked, the server redirects you to a different page, such as http://mysite.com/about-me
. As a result, the active page's URL does not match the href of the random button, causing it to not receive the active state.
One could question whether the random button should even receive the active state since clicking it again may not take you to the same page. Nevertheless, let’s address how this can be resolved.
I see two possible solutions:
Server-Side Solution:
Instead of redirecting directly to http://mysite.com/about-me
, consider redirecting to
http://mysite.com/about-me?random
. By adding this query parameter, the link’s behavior should remain unaffected (unless there are strict controllers or if that variable is utilized). With JavaScript, you can detect the presence of this variable in the URL and activate the random button accordingly.
Here’s an example implementation:
$(document).ready(function(){
var url = document.URL;
// Check for 'random' in URL
if (url.indexOf('?random') >= 0) {
$('#topbar a.random').addClass('active');
}
// Check all other links
$('#topbar a:not(.random)').each(function(){
if($(this).attr('href').indexOf(url) >= 0){
$(this).addClass('active');
}
else{
$(this).addClass('inactive');
};
});
});
Cookies Solution:
If server-side changes are not feasible, you can achieve this entirely through JavaScript using cookies. Upon clicking the random button, set a ‘random’ cookie to true before proceeding with the link action. When the page loads, check if this cookie is set to true – if so, deactivate it and mark the random button as active.
While using cookies is not always recommended (as they are sent with every page request, potentially raising privacy concerns), it could be a viable last resort option. If you prefer this approach and need further assistance, feel free to ask for help.