william44isme
william44isme

Reputation: 877

Scroll to jQuery functions weirdly

I have a jQuery smooth scroll script:

$(".scroll").click(function(event){
     event.preventDefault();
     var dest=0;
     if($(this.hash).offset().top > $(document).height()-$(window).height()){
          dest=$(document).height()-$(window).height();
     }else{
          dest=$(this.hash).offset().top;
     }
     $('html,body').animate({scrollTop:dest}, 500,'swing');
 });

It scrolls fine to

<a id="info"></a>

But doesn't work on any of my others

<a id="top"></a>
<a id="bottom"></a>
<a id="announcements"></a>
etc ...

When manually adding domain.com/#top it works, so the anchors should be fine.

Does anyone know why?

Live preview: http://thehtmlworkshop.com/

Upvotes: 0

Views: 399

Answers (3)

Todd
Todd

Reputation: 5454

Here's a jsfiddle: This works.

The JQuery:

$(".scroll").click(function(event){

var target = $(this).hash;
 var dest=null;
 if(($(this.hash).offset().top) > ($(document).height()-$(window).height())){
      dest= $(document).height()-$(window).height();
 }else{
      dest=$(this.hash).offset().top;
 }

$('html,body').animate({scrollTop:dest}, 1000, 'swing');
 event.preventDefault();

});

Upvotes: 0

Kasyx
Kasyx

Reputation: 3200

Your buttons top and down has no class scroll. Try to add it.

<a href="top" class="scroll" /><!-- img --></a>

And then to be sure, that the a will fire event:

$("a.scroll").click(function(event){
    //your code there
});

Upvotes: 1

hellojosh
hellojosh

Reputation: 21

The problem is that you are settings the click to class of 'scroll'. The click event needs to be set to the parent.

$(".scroll").parent().click(function(event){
     event.preventDefault();
     var dest=0;
     if($(this.hash).offset().top > $(document).height()-$(window).height()){
          dest=$(document).height()-$(window).height();
     }else{
          dest=$(this.hash).offset().top;
     }
     $('html,body').animate({scrollTop:dest}, 500,'swing');
});

Upvotes: 1

Related Questions