0

I want to scroll smoothly when I click the navbar, so they have an href of #blahblah for where to go.

My current code, which won't work, is as follows:

$(".menu").click(function() {
    var href = $(this).attr('href');
    $('html, body').animate({
        scrollTop: $(href).offset().top
    }, 2000);
});
isherwood
  • 52,576
  • 15
  • 105
  • 143

3 Answers3

0

I think you want this, so you're selecting an ID:

scrollTop: $('#' + href).offset().top
isherwood
  • 52,576
  • 15
  • 105
  • 143
0

Pass correct string thats it

$(".menu").click(function() {
var href = $(this).attr('href');
$('html, body').animate({
    scrollTop: $("#"+href).offset().top
}, 2000);
});
Trishul
  • 958
  • 1
  • 7
  • 17
0

This shows my answer: http://jsfiddle.net/ZjQLy/

html:

<div id="click" href="#tar">click me</div>
<div id="space"></div>
<div id="tar">whats up</div>

javascript:

$("div#click").on("click", function () {
  $("html, body").animate({
      scrollTop: $($("div#click").attr("href")).offset().top
  }, 2000);
});

Additionally, here is another stack overflow question that has an answer: JQuery smooth scrolling to one element when clicking a corresponding element

Community
  • 1
  • 1
Fallenreaper
  • 9,420
  • 12
  • 58
  • 116