Reputation: 43
I know there are already answers to this, but I searched and none is working and I don't know why.
So what I wanted is a smooth scroll to a div by the tag
What I wanted was like this
So I took the js code but on me isn't working at all, the scroll loses his effect at all.
Here is my code: w HTML
<div class="col-lg-3 col-md-3 col-sm-3" id="some">
<a href="#info" id="normal">
<img src="imgs/product/normal.png" class="img-responsive">
</a>
</div>
<!-- OTHER CONTENT -->
<div id="info">
Go here
</div>
And the JS:
$("#some a[href^='#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// animate
$('html, body').animate({
scrollTop: $(this.hash).offset().top
}, 300, function() {
// when done, add hash to url
// (default click behaviour)
window.location.hash = this.hash;
});
});
Upvotes: 1
Views: 631
Reputation: 3836
Just use below code snippet to achieve as you mentioned in post.
$(function() {
$('a').bind('click',function(event){
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1000);
event.preventDefault();
});
});
Upvotes: 0
Reputation: 2865
That is before you have a link inside. BTW look at your console, is there any error messages?
Change your code to:
$("#some a").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
var id = $(this).attr("href");
// animate
$('html, body').animate({
scrollTop: $(id).offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = this.hash;
});
});
Upvotes: 0
Reputation: 490
I don't know if you copy > paste your code but you're missing a quote before the id:
<div class="col-lg-3 col-md-3 col-sm-3 id="some">
That could be a solution why it's not working because $('#some a')
doesn't exist then.
Upvotes: 2