Scroll to a div using jQuery from other page - javascript

When I click href #demo-1 from home page to another page with ection id='demo-1'.
How when loading the page with id='demo-1', that it will scroll down from the top of the page.
If I use https://stackoverflow.com/a/3432718/6891215 it will jerk and not scroll from the top of the page down to that section.
Many thanks!

The code below allows you to scroll on both same and external pages. To make the link work you need to give it a class .scroll. If you're linking to an anchor link on an external page, give the link a data-target="external" as well.
$(document).ready(function() {
$('html, body').scrollTop(0);
var str = window.location.href;
if(str.indexOf('#') > -1) {
var anchor = str.substring(str.indexOf('#'));
setTimeout(function() {
$('html, body').animate({scrollTop: $(anchor).offset().top}, 'slow');
}, 100);
}
$('a.scroll').click(function(e) {
var trg = $(this).attr('data-target');
if(trg != 'external') {
e.preventDefault();
var href = $(this).attr('href');
$('html, body').animate({scrollTop: $(href).offset().top}, 'slow');
}
});
});
The link to an anchor on an external page will look like this:
DEMO 2
Also, you can link to an anchor on the same page. In this case, you won't need to add any data-target. I wrote the script the way that is supports both:
Go TO DEMO 3

Related

Scroll to anchor with slash at the end

I have a website where sections have # and menu items should scroll to them. Due to setup of website it's required that my URL have / (slash) at the end.
For example website.com/about/
So anchor would be website.com/about/#team/
When there's / at the end of URL, scroll to anchor doesn't work. I don't have any jQuery on website so simple jump to section doesn't work either. When I remove / it works.
Is there jQuery which I can use for that purpose? I tried bunch of jQuery but without success.
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
});
});
As you said you cant change hash pattern then you have to do reverse process: remove dash from this.hash before putting $(hash).offset() method
$(document).ready(function(){
$('a').click(function(event) {
// Store hash
event.preventDefault();
var hashWithoutDash = this.hash.replace("/",""); // remove dash from hash to make $(hashWithoutDash).offset() worked
$('html, body').animate({
scrollTop: $(hashWithoutDash).offset().top
}, 1000, function() {
window.location.hash = this.hash; // keep actual hash with dash
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<p id="team">This is a paragraph.</p>
<div style ="height:1000px"> please scroll down to see href link </div>
team
<button>Return the offset coordinates of the p element</button>

Remove anchor link after scrolling - works also on links from another page

I've set up a single page website with smooth scrolling that strips the anchor link from the URL after smooth scrolling. Here's the jQuery I'm using :
$(function() {
$('a.page-scroll').on('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 60
}, 1000, 'easeInOutExpo');
event.preventDefault();
});
});
Everything works great until I added other pages. I can't get the anchor link to strip out after a link like <a class="page-scroll" href="../#contact">Contact</a> on another external page.
I've searched high and low on SO but can't find a solution that works.
I don't totally care about the smooth scrolling if the link is from an external page. What I need most is to navigate / scroll to the id section of the main page (with offset to accommodate fixed navigation) and remove the anchor link from the browser URL window when the link is from an external page (from other pages on my website, or from other websites).
I've tried this also, but it likewise only works on internal links on to an id on the same page :
<script>
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
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) {
$('html,body').animate({
scrollTop: target.offset().top - 60
}, 1000);
return false;
}
}
});
});
</script>
I've also tried this with no luck :
<script type="text/javascript">
(function($) {
$(document).ready(function() {
var url=document.URL.split("#");
var ancher=url[1];
$('html, body').animate({
'scrollTop': $('#'+ancher).offset().top - 60
}, 5000);
});
})(jQuery);
</script>
Any New Year's Eve help would be most appreciated so I can get this project wrapped up!
It's possible I don't understand the extent of the question, but I believe you are trying to make it so the href doesn't fire on pages that are wanting to scroll but does on pages that are linking to other pages and not sections within the page itself. Perhaps something like this would work for you:
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
if ($anchor[0].href[0] === '#') {
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 60
}, 1000, 'easeInOutExpo');
event.preventDefault();
return false;
} else {
return true;
}
});
});
What this does is look to see that the leading character in the href is a # implying that its a link to a section within itself.
Let me know if that helps and/or if I'm on the right track.
ps: I left the .bind in there because I don't know what version of jQuery you are on, but the newer syntax is to use .on
Happy New Year
Just to append slightly in regards to making it so that deep links to the main page go to the appropriate section but don't have the hash tag:
You can remove that 'hash' variable from window.location, but if you attempt to remove the hashtag entirely, it will cause the browser to refresh. This will also cause the viewer to lose the spot (thus removing the deep link's purpose).
To change the hash tag value (keeps the #):
window.location.hash = ''; // clears the hash tag
To remove the hash tag and its value (clears the # and everything past it):
window.location.href = window.location.href.substr(0, window.location.href.indexOf('#')); // this causes a browser refresh
And if it's not wholly apparent, you would run it on page load
$(document).ready(function() {
if (typeof(window.location.hash) !== 'undefined' && window.location.hash.length > 0) {
window.location.hash = ''; // will clear the hash anytime someone arrives with a hash tag
}
});
For a page with smooth scrolling try to use replaceState().
It will remove the hashtag at anchor link from the browser URL window (without page reloading).
// smooth scrolling
function scrollTo(selectors)
{
if(!$(selectors).length) return;
var selector_top = $(selectors).offset().top - 0;
$('html,body').animate({ scrollTop: selector_top }, 'slow');
}
// do scroll and clear the hash tag
$(window).on('load', function(){
if( typeof(location.hash) !== 'undefined' && location.hash.length ) {
scrollTo(location.hash);
history.replaceState(null, null, location.pathname);
}
});

jQuery single page scrolling with links to other pages

I have a site with most of it's content in a single page style with menu links that scroll down the page using the div ID as the anchor (for example www.mydomain.com/#div-id) There are, however, some extra external pages that are also linked in the header.
The issue I'm having is that when I'm on one of the external pages (for example, www.mydomain.com/page-1) the menu links that are used to scroll down the home page don't work (they come out as www.mydomain.com/page-1/#div-id).
jQuery(document).ready(function($){
jQuery('a[href*=#]').click(function (e){
e.preventDefault();
var navHeight = jQuery('.header-site').height();
var id = jQuery(this).attr('rel');
var scrollTo = jQuery('#' + id).offset().top-navHeight;
jQuery('html,body').animate({
'scrollTop': scrollTo
}, 500);
});
});
I use the link rel attribute to add the div ID so that I don't conflict with other jQuery plugins such as tabs.
Is there a way to solve my issue, so that I can have menu items that scroll to the page, ut when I'm not on the main page, the 'scrollable' menu items link back to the front page (and to the relevant section).
As they are all on the homepage, change your hrefs to start with /:-
test
That will stop this problem - www.mydomain.com/page-1/#div-id
Then split your function out so it can be called on page load and on click, and only preventDefault if you are on the homepage, otherwise let it redirect you to the homepage with the hash.
as all hrefs will now be /# I'm using jQuery('a[href^="/#"]')
function scrollToSection(id) {
var navHeight = jQuery('.header-site').height();
var scrollTo = jQuery('#' + id).offset().top - navHeight;
jQuery('html,body').animate({
'scrollTop': scrollTo
}, 500);
}
jQuery(document).ready(function($) {
var isHomepage = window.location.pathname == '/';
if (isHomepage && window.location.hash) {
var id = window.location.hash.split('#')[1];
scrollToSection(id);
}
jQuery('a[href^="/#"]').click(function(e) {
if (isHomepage) {
e.preventDefault();
var id = $(this).attr('href').split('#')[1];
scrollToSection(id);
}
});
});
Code snippet to give an idea:
jQuery(document).ready(function($) {
jQuery('a[href*=#]').click(function(e) {
//main page found
if (document.location.pathname == "/") {
e.preventDefault();
var navHeight = jQuery('.header-site').height();
var id = jQuery(this).attr('rel');
var scrollTo = jQuery('#' + id).offset().top - navHeight;
jQuery('html,body').animate({
'scrollTop': scrollTo
}, 500);
});
}
});

Smooth Scroll works only from the same page and not from external links

I am using this code to a wordpress paid theme (Gavick - Creativity) and it uses the code below:
jQuery(document).ready(function () {
// SmoothScroll jQUery substitue
jQuery('a[href^="#"]').click(function (e) {
e.preventDefault();
var target = this.hash,
$target = jQuery(target);
if ($target.length) {
jQuery('html, body').stop().animate({
'scrollTop': $target.offset().top + 150
//'scrollTop': $target.offset().top ORIGINAL
}, 1000, 'swing', function () {
window.location.hash = target+150;
//window.location.hash = target; ORIGINAL
});
} else {
window.location.hash = target;
// window.location.hash = target; ORIGINAL
}
});
The thing is that it smooth scrolls only from internal links and not from external.
When I am at the same page and click on an anchor link it scrolls perfectly.
Visiting the page anchor from another page doesn't scroll at all.
All I need is to visit http://domain.com/#anchortag and scroll to it from the start of the page.
I also need to be able to have different offsets if I am in the same page or in an external one.
Any help?
Well first thing
Visiting the page anchor from another page doesn't scroll at all.
You can make a jQuery function to check for that case:
function checkForAnchor() {
var pathname = jQuery(location).attr('href');
pathname = pathname.split("#");
for(var i = 0; i < pathname.length; i++){
if(pathname[i] == 'YOUR ANCHOR'){
jQuery('html, body').animate({ scrollTop: (jQuery('.YOUR CONTAINER TO SCROLL TO').offset().top)}, 'slow');
}
}
}
I also need to be able to have different offsets if I am in the same page or in an external one.
Therefore you may use a cookie. When the user visits your page first and there is no cookie you can use another offset to scroll to. After that set a cookie and use a different offset.

Navigate slow to id in URL

On my homepage I have a menu with ID's, when I click it, it slides to the corresponding div and it works smoot.
But when I'm not on my homepage and I click an item I want to be able to go to the homepage and then slide to the section.
Here is the code I'm using now:
$('#mainMenu a').click(function(e){
e.preventDefault();
var div = $(this).attr('href');
if('<?=get_site_url()?>/' == '<?=get_permalink()?>')
{
$('html, body').animate({scrollTop:$(div).position().top}, 'slow');
}
else
{
window.location.href = '<?=get_site_url()?>/'+div;
}
});
This works excellent, the next part works to but I can't get it to slide to the ID.
if (window.location.hash != "") {
e.preventDefault();
$('html, body').animate({scrollTop:$(window.location.hash).position().top}, 'slow');
}
Is there a way I can prevent the browser from directly jumping to the section and instead sliding to it?
Try to scroll to top right at the start, then roll down:
if (window.location.hash != "") {
$('html, body').scrollTop(0).animate({scrollTop:$(window.location.hash).position().top}, 'slow');
}
Also, remove e.preventDefault(), since you're not defining any variable named e nor an event.
This works like a charm:
$('#mainMenu a').click(function(e){
e.preventDefault();
var div = $(this).attr('href');
if('<?=get_site_url()?>/' == '<?=get_permalink()?>')
{
$('html, body').animate({scrollTop:$(div).position().top}, 'slow');
}
else
{
localStorage.setItem("hash", div);
window.location.href = '<?=get_site_url()?>/';
}
});
if (localStorage.getItem("hash")!=null) {
$('html, body').animate({scrollTop:$(localStorage.getItem("hash")).position().top}, 'slow');
localStorage.removeItem("hash");
}
Instead of putting the hash in my url I stored it in localStorage and in my head of the page I checked if it was set.
Founded this solution just a few minutes after posting the question, thanks to those who helped me :)

Categories

Resources