Reputation: 1878
How can I adjust the javascript I have to scroll to an anchor point but also include an offset. I have added a rule for offset of 200px but nothing works.
$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top - 200;
}, 1000, function() {
var $target = $(target);
$target.focus();
if ($target.is(":focus")) {
return false;
} else {
$target.attr('tabindex','-1');
$target.focus();
};
});
}
}
});
Upvotes: 0
Views: 34
Reputation: 4400
Check below snippet for simple example using jquery.
$('a').click(function(evt) {
evt.preventDefault();
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top - 50
}, 800, function() {});
});
.empty {
height: 500px;
width: 100%;
background: #ccc;
}
#content {
height: 200px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#content">Click Me!</a>
<div class="empty"></div>
<div id="content">
Content goes here.!
</div>
<div class="empty"></div>
Upvotes: 1