• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

138
Vistas
How can I avoid infinite loop when reformatting url hash with Jquery event 'hashchange'

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>
almost 3 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda