Search code examples
jqueryscrollanchorpreventdefault

Prevent go to anchor link using jQuery


This is my jQuery code, when it reads the window.location.hash it adds a CSS class to an element and it is shown. But I cannot do to prevent going to that anchor. I tried preventDefault() but it seems to not work.

<script type="text/javascript">
function cotizar(n){
  gotoSlide(n);
  $('#cotizadores > div').removeClass();
  $('#cotizadores > div').eq(n).addClass("cotizador_activo");

}

$(document).ready(function() {
  if(window.location.hash != ''){ 
    var hash = window.location.hash.substring(1);
    index = $(".tab-content > div ").children("#boton_"+hash).index();
    cotizar(index);
    clearInterval(slideival);
}

$(".slides > div > a").on('click',function(event){
  window.location.hash = $(this).parent().attr('id');
  index = $(this).parent().index();
  cotizar(index);
  event.preventDefault();
  return false;
});


});
</script>

This is my site url, try clicking 'ABRIR COTIZADOR' in any of the slides.

Thanks!


Solution

  • Thanks to Alexander O'Mara, this is the best answer I found:

    el= $('#anchor_element');    
    id= el.attr("id");    
    el.removeAttr('id');
    window.location.hash =id;
    el.attr('id',id);
    

    This option prevent flickering. Credits to Tobias Buschor, seen in Lea Verou Blog's comments