2

So I'm trying to make it that then when you click a link in a carousel it scrolls you down the page to the content.

Here is my jquery:

$('#picks li a').click(function(){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    return false;
});

However I recieve this error in my console Error: Syntax error, unrecognized expression: http://hutchcreative.co.uk/rod/other/#galleryDetails

That is the correct link location but not sure how to correct it so that jquery adds in the slide?

Thanks!

probablybest
  • 1,403
  • 2
  • 24
  • 47

4 Answers4

5

If the attribute href is referencing the id of an element, you need to use the # before the actuall ID

$('#picks li a').click(function(){
    $('html, body').animate({
        scrollTop: $( '#'+$.attr(this, 'href') ).offset().top
    }, 500);
    return false;
});

Also note, that this will be triggered twice; I know you added html in order to work with firefox, as I Did a while a go,

So you could:

$('#picks li a').click(function(){
        $(Query.browser.mozilla ? "html" : "body").animate({
            scrollTop: $( '#'+$.attr(this, 'href') ).offset().top
        }, 500);
        return false;
    });

or, at least stop the animation before:

$('#picks li a').click(function(){
        $('html, body').stop(true,true).animate({
            scrollTop: $( '#'+$.attr(this, 'href') ).offset().top
        }, 500);
        return false;
    });

To prevent some issues with this double call

Community
  • 1
  • 1
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378
0

The attr method is returning a string with the entire URL. You need to get rid of everything before the "#" in the string. You can use indexOf to find the index of the "#" character, and you can use substr to get only the portion of the string you want.

sbking
  • 7,630
  • 24
  • 33
0

Well when I go to your link, the first problem i get is that $ is undefined, when i try to test from console. However jQuery works fine, so your lib is obviously loaded.

The next prob is you code. You're calling for href which is getting the whole link and not just the hash mark.

jQuery('#picks li a').click(function(e){
    e.preventDefault();
    var id = $(this).attr('href').split('#');
    id = '#' + id[id.length-1];
    jQuery('html, body').animate({
        scrollTop: $( id ).offset().top
    }, 500);
    return false;
});
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
0

I tried several ways, none worked.

For me this works with Angularjs combined.

$( "html, body" ).scrollTop( $("#main_div").offset().top );

main_div is the id in any HTML element you want.

I don't like Angularjs hashtags at the top of the URL, that's why I didn't use them.

$location.hash('main_div');

I think the animate thing complicates this.

halfer
  • 19,824
  • 17
  • 99
  • 186
Brian Sanchez
  • 832
  • 1
  • 13
  • 11