Reputation: 2129
I have a main menu which is displaying on every page of the site. One link in that menu is linked to a specific div on the home page.
I want when I click on that link it should scroll to 50 pixels above that div.
So when I am on the home page then when I click on it, it should scroll smoothly to 50 pixels above that specific div.
And when I am on a different page and click on that link it should redirected to home page and scroll to 50 pixels above that specific div.
Code I have tried
<a href='/#element_id'>Link</a>
$('a').click(function() {
var divLoc = $('#element_id').offset();
$('html, body').animate({
scrollTop: divLoc.top-50}, "slow");
});
but this only work when I am on the home page as that specific div is on home page.
Any I idea how to do this?
Upvotes: 2
Views: 3433
Reputation: 11671
Add to your link a url of the format http://mysite.com/homepage/#the-div-class-i-want-to-scroll-to
Then add this js code to your homepage head section
$(document).ready(function(){
/*if you use the id of the div no need for the replace*/
var target = $(document.location.hash.replace("#","."));
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top-50
}, 1000);/*animate in 1sec, you may change this as you like*/
}
});
I just noticed that this is what you have tried, so make sure you place the js code at the correct place of your homepage, i.e. load js in head within document ready.
Upvotes: 1
Reputation: 19232
Instead of using an element id match, just use a name value for the anchor tag to scroll too:
$('.scroll-anchor').click(function () {
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
<a class="scroll-anchor" href="#myreusableanchorname">My Resuable scroll for each page</a>
<a name="myreusableanchorname"></a>
Upvotes: 1
Reputation: 363
I have done this before on my company website, check www.CreaDevSolutions.com, then chose a service from the services menu, it will take you there and will scroll smoothly using jquery animate to the service description.
the idea is very simple:
1- you need a communication way between both pages via serverside code or via Url parameters,or cookies, i used Url Parameters, and what i pass is the element Id.
2- when the page loads check if there are any variables in the url param are pointing somewhere (check the line 552 getUrlVars()).
3- if there is a value retrieved then i call function animateToElement() which is on line 557
Upvotes: 0