Issue Background
I have set up my webpage to use identifiers with prefix #s-
to differentiate anchor links from other page identifiers. The window.location.hash
changes to hash which moves the frame to the content in focus but also triggers the hashchange
listener causing a loop.
What I've tried
I have it working for whenever the hash has changed but the only instance it does not work is when the same link it pressed (as I use this in the condition to stop the infinite loop). The code for this was:
$(window).on('hashchange', function(e) {
if ($(location).attr('hash') != last_hash) {
manageHash()
}
});
What I want
I'd like to be about to find a condition or method to allow users to select a link to change the hash but also allow them to re-select the same link as many times as they want without causing a loop.
JS
last_hash = ''
function manageHash() {
var hash = $(location).attr('hash');
if($('#s-'+hash.substring(1)).length != 0 && '#s-'+hash.substring(1) != '#s-' ) {
last_hash = hash
window.location.hash = '#s-'+hash.substring(1);
}
}
$(window).on('hashchange', function(e) {
if ($(location).attr('hash') != last_hash) {
manageHash()
}
});
$(document).ready(function() {
manageHash()
})
HTML
<div class="contentSubSectionContainer contentSubSection" id="s-{{ subsection.slug }}">
<h2 class="contentSubSectionFont1Bold">{{ subsection.sub_section_title }}:</h2>
<div class="contentSubSectionContentFont1">
{{ subsection.content_rendered|safe }}
</div>
</div>