Smooth scroll prevent me from leaving page

I am new to Jquery so for now I try to use already made code and understand it. I was using a smooth scroll code but it prevents me from leaving the page if I don't remove


However, if I do remove it it goes blank for a third of a second because it goes to the anchor and then executes the scrolling.

Here is the code:

 $("a").on('click', function(event) {
 if (this.hash !== ""){ //here is my problem I think
  //Prevent default anchor click behavior
  event.preventDefault(); //here is what makes me unable to leave page
  var hash = this.hash;
  $('html, body').animate({
   scrollTop: $(hash).offset().top
  }, 800, function(){
   window.location.hash = hash;
  } // End if

What I wanted to do was :

if(this.hash !== "" && this.split('#')[0] != location.split('#')[0])

But then the code just doesn't execute, I tried several other way, but as soon as I try to manipulate 'this', even if I put it in an other variable and then manipulate the variable, it won't work.

So, how do I access other pages with the "event.preventDefault()"?

Thank you

Answers 1

  • You can change that if statement to this...

    if (this.hash !== "" && this.href.split('#')[0] != location.href.split('#')[0])

    And that should work.

Related Articles