First off thanks for taking the time to read my question. I'm trying to make a normal link (href), link back one page and scroll to an div id
. I've been looking at this question: Here. Which does exactly what I want. So I've linked the JavaScript file in my header and placed the jQuery code in my footer. But it does nothing.
This is my link:
<div class="col-xs-4 text-center">
<a href="/the_liked_page/" data-id="my_id" class="gobackandscroll"><i class="fa fa-th-large fa-2x" aria-hidden="true"></i><br>Go back</a>
</div>
Nothing fancy... and here is the script:
// Read the cookie and if it's defined scroll to id
var scroll = jQuery.cookie('scroll');
if(scroll){
scrollToID(scroll, 1000);
jQuery.removeCookie('scroll');
}
// Handle event onclick, setting the cookie when the href != #
jQuery('.gobackandscroll').click(function (e) {
e.preventDefault();
var id = jQuery(this).data('id');
var href = jQuery(this).attr('href');
if(href === '#'){
scrollToID(id, 1000);
}else{
jQuery.cookie('scroll', id);
window.location.href = href;
}
});
// scrollToID function
function scrollToID(id, speed) {
var offSet = 65;
var obj = jQuery('#' + id).offset();
var targetOffset = obj.top - offSet;
jQuery('html,body').animate({ scrollTop: targetOffset }, speed);
};
I don't get any errors in my console.log and it links to the page I want. But there is no scrolling.
When I delete all the data and mark up both pages like this: http://plnkr.co/edit/l2aassM4biyNRWNCrvUz?p=preview it does work. So the JavaScript is correctly loaded and storing the cookie.
So I thought maybe the data-id is not stored so I've put an alert on the click using:
alert(id);
This gives the correct data-id
but this doesn't scroll on the next page. Does anyone have an idea why this isn't working or a better suggestion for this? Thanks of the help...