Tony Tony - 3 months ago 7
jQuery Question

Jquery anchor href affects whole site

I am new in jquery and am trying to use the jquery anchor code, which was written by Cedric Dugas for my site. It works well, but if I have a custom link, which does not use #, then that link won't be redirect to anywhere.

So, as far as i understand that the event.preventDefault() which blocks the google link to be opened and i don't know how to override this. Please help me! Thank you.



/*******

*** Anchor Slider by Cedric Dugas ***
*** Http://www.position-absolute.com ***

Never have an anchor jumping your content, slide it.

Don't forget to put an id to your anchor !
You can use and modify this script for any project you want, but please leave this comment as credit.

~ MODIFIED! ~ 

*****/


jQuery.fn.anchorAnimate = function(settings) {

settings = jQuery.extend({
speed : 500,
offset : 0
}, settings);

return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault();
var locationHref = window.location.href;
var elementClick = $(caller).attr("href");

var destination = $(elementClick).offset().top - settings.offset;

if (destination < 0) {
destination = 0;
}

$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {

});
return false;
})
})
}

<div>
<ul>
<li>
<a href="#link1"> Homepage </a>
</li>
</ul>
<ul>
<li>
<a href="#link2"> Product </a>
</li>
</ul>
<ul>
<li>
<a href="#link3"> About us </a>
</li>
</ul>
</div>
<div>
<ul>
<li>
<a href="https://www.google.com"> Google link </a>
</li>
</ul>
</div>




Answer

Basically you need to check if the link is a has or not.

You can do this in many ways, I'm going to post one of the simplest ways. You can simply surround the code block in this code if($(caller).attr("href").charAt(0) == "#"){}. It just simply checks if the first character in the href is a #, if it is, go ahead else do nothing.

jQuery.fn.anchorAnimate = function(settings) {

   settings = jQuery.extend({
      speed : 500,
      offset : 0
   }, settings);  

   return this.each(function(){
      var caller = this
      $(caller).click(function (event) {  
          if($(caller).attr("href").charAt(0) == "#"){
            event.preventDefault();
         var locationHref = window.location.href;
         var elementClick = $(caller).attr("href");

         var destination = $(elementClick).offset().top - settings.offset;

         if (destination < 0) {
            destination = 0;
         }

         $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {

         });
         return false;
        }
      })

   })
Comments