Jquery animate method doesn't run under certain circumstances - javascript

I'm using a jQuery's animate method to create a smooth scrolling effect to make a navigation bar's links scroll to particular spots on the homepage. ...in case there's confusion on what I'm talking about, here's a better description.
Here's the little bit of javascript I'm using to accomplish this effect:
$(document).ready(function(){
$('a[href^="/#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top-$('.navbar').height()
}, 1000, 'swing', function () {
window.location.hash = target-$('.navbar').height();
});
});
});
Our home button is:
<a class="navbar-brand" href="/#home_top"></a>
And our about us link is:
About
Anyway, when I just type in the url and navigate directly to domain.com the scrolling function works great. I can scroll down to the "About Us" section (or any other) and click our home button to go back to the top of the page.
The problem comes when I use the home button to navigate to the homepage from one of the other pages on the site. Say, for example, I'm at domain.com/another_page and I click on the home button to get back to the homepage at domain.com. The homepage loads but the javascript for the scrolling doesn't work. Only once I refresh does it work again; then everything's fine.
Anyway, sorry if the question's a bit convoluted. Any help on the matter would be appreciated.

Related

How can I refresh a page and not retain the anchor position with Jquery

The issue I am having:
Within my nav bar on my site I have a hamburger menu that contains 2 items:
Contact
Testimonials
From my hamburger menu drop down, I select the anchor tag labeled Testimonials.
Jquery applies a smooth scroll top to the anchor element and a hash will be placed to end of the URL like below:
https://example.com/#123456
Here is the code I currently have:
$(document).on("click",'.super-navbar__actions', function() {
var testimonialsLink = $('.super-navbar__menu-item-list a:nth-child(2)');
$(testimonialsLink).attr('href',"#block-9d888965d45244f4a0ebb3d7ded725bc");
$(testimonialsLink).removeAttr("target");
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var targetEle = this.hash;
var $targetEle = $(targetEle);
$('html, body').stop().animate({
'scrollTop': $targetEle.offset().top-100
}, 800, 'swing', function () {
window.location.hash = targetEle;
});
});
});
Goals:
I'd like to have the ability to refresh the page and start at the top of the existing page as if I had never selected the anchor link from the hamburger menu.(Currently upon reload the page will begin at the last anchor position which is halfway down the page which i not he best experience)
I'd like the ability to navigate back to the home page without the browser automatically anchoring me to the previously selected anchor position.
Lastly, within the navbar hamburger selection Testimonials, I'd like to be able to navigate to the testimonials section from other pages.
I am totally stuck with this one and have looked high and low to find an elegant solution with Jquery.
I have tried:
How to disable anchor "jump" when loading a page?
append /remove anchor name from current url without refresh
Attempting to remove anchor tags from the URL
Remove anchor link after scrolling - works also on links from another page
How to refresh a page and load at top after an anchor has been clicked, ignoring the anchor, and resetting back to the top?
With no luck :/

Wordpress Divi Theme - Anchor link to accordion toggle

I am trying to get an anchor link to direct to an accordion, and open the toggle.
I've found a code snippet on google that sort of works, but not entirely.
When I am on the page that the accordion is on, and I click on the anchor link, it correctly scrolls to the accordion and opens the tab --- however, it refreshes the page at this time and does not stay where the accordion is.
If I click on the anchor link from another page other than the one that the accordion is on, all it does is direct me to that page -- not the accordion.
Any assistance with the would be great.
The URL is http://casafamilyserv.wpengine.com/resources/
The anchor link is the 'Make a donation' button in the upper right hand corner of the page.
here is the JS snippet:
<script>
jQuery(function($) {
//accordion
$('.menu-item-98 a').on('click', function(event){
$('#my-accordion .et_pb_accordion_item_2 .et_pb_toggle_title').click();
$("html, body").animate({ scrollTop: $('#my-accordion').offset().top }, 1000);
});
});
</script>
The anchor link is to open the 'contribute / donate' accordion tab.
Just add return false;.
$('.menu-item-98 a').on('click', function(event){
// sometimes you may also need to add
// event.preventDefault();
donateScroll();
return false;
});
This is happening because your donate button has a #donate in the url.
Make A Donation
By default, browsers will try to find id="donate" somewhere on the page and jump to it. Adding return false; blocks that default behavior and allows your js to have full control over the click event.
You can also add something to check for existing hash when arriving from a different page:
function donateScroll(){
$('#my-accordion .et_pb_accordion_item_2 .et_pb_toggle_title').click();
$("html, body").animate({ scrollTop: $('#my-accordion').offset().top }, 1000);
}
if(window.location.hash == '#donate') {
donateScroll();
}
Instead of repeating your scroll and click logic, you can also move it into a reusable function.

Trying to get this wordpress theme to scroll to an id when a link is clicked on a different page

Easiest way to explain it is if you have a look at the site - haloespresso.com.au/working/
If you click the "menu" option in the top menu, it scrolls to the menu id #pg-9-4, which is what I want. On the other pages, the menu is slightly different and the same link is changed to link to the home page with #pg-9-4 added to the end of it. The point here is clearly to get the link from another page to open the home page but scroll to the menu part of it. I don't even need it to smooth scroll or anything, just go to that spot. It looks like it does go there for like, one frame, as it's loading, but it keeps jumping to the top. It's simply beyond me to try and figure out what is causing it to lose this basic HTML (afaik) functionality and keep forcing me to the top of the page...
Any help would be really great, as I'm a bit of a noob when it comes to anything other than html/css and simple jquery.
Just append the anchor to the end of the link.
Simply insert a link like:
Link to section on another page
Edit: Just noticed you're not getting this to work. What do your links look like, and what's the HTML with the ID on the target page?
Try this jQuery code:
$(document).ready(function() {
function hashScroll() {
// get URL Hash
var hash = window.location.hash;
// check if hash is set and not empty
if (hash != '') {
// scroll to hash ID after 10ms delay
setTimeout(function() {
$(document).scrollTop( $(hash).offset().top );
}, 10);
// debugging
console.log(hash);
console.log('offset:'+ $(hash).offset().top );
}
}
hashScroll(); // fire hash scroll function
});
Explanation:
This function will capture the URL hash (www.example.com/#hash), checks if it's not empty and then scrolls the page to the element with the ID which matches the hash after 10 ms. The delay is there to make sure browsers don't mess up the loading process.

Scroll to div on page load while using pjax

So i'm using pjax so when a user clicks a link instead of loading a new page it will drag the content in. The content has a navigation bar at the top with the content underneath. Upon click the navigation bar it hides and displays certain contents.. that is working fine.
My problem. When the content is dragged in, I want the page to scroll straight to the navigation bar instead of sticking at the top of the page and the user needs to scroll to it. I've used:
$(function() {
$('html, body').animate({
scrollTop: $('#in-page-nav').offset().top}, 1000);
});
To scroll to the div on the page load, and it works fine when I refresh the page. But doesn't work when pjax pulls the content into the page.
Any help i'd be really grateful, thank you!
You could do your animation in the pjax:success event. pjax:success is fired:
after replacing HTML content loaded from the server
Example
$(document).on('pjax:success', function() {
// Your scroll animation here.
})
See Pjax events for more details.
FIXED
Okay so I'm not sure if anyone has/had this problem but just for reference sake and if anyone comes across this problem heres what I did:
I looked at pjax documentation;
complete - When AJAX request has completed
success - When AJAX request has completed successfully
are two of the callbacks which can be used.
pjax.connect({
'success': function(e){
window.location.hash = $('#in-page-nav a').eq(0).attr('href');
// $(function() {
$('html, body').animate({
scrollTop: $('#in-page-nav').offset().top}, 1000);
},
});
So my previous code which animate scroll to a div on page load copied that and placed this within the pjax.connent and used the success callback. This works perfectly. I kept the code to animate on page load as well so if a user bookmarks the link or sends it and uses the link directly. Then the page will load the same.
Thanks for the quick responses!

Execute javascript function on anchor click, but the code must run on the page opened by that anchor

Is this behaviour possible? I would need the code that is inside on click event handler, to be executed on the new HTML page that is opened by that navigation link.
I've put up a small fiddle to better illustrate what I want to achieve.
http://jsfiddle.net/hWEpL/4/
Here is the jQuery for scrolling:
$.fn.scrollView = function () {
return this.each(function () {
$('html, body').animate({
scrollTop: $(this).offset().top
}, 1000);
});
}
$('#link-3').click(function (event) {
event.preventDefault();
$('.section-3').scrollView();
});
Let's assume that the fiddle is Home Page. When clicking on Section-3, the page scrolls to section-3.
Now, let's say the we are on the second page(about) and we click on Section-3. I would like to have Home Page opened, and that the page is scrolled to section-3.
The thing is that I don't want this behaviour when the Home Page is opened, I only need it when someone is on the other pages and clicks on Section-3
You can use Fragment identifiers. So in the about page for example, you would link to the home page with homepage.htm#section-3 and in homepage.htm, you would include just like the code you have included but add
var hash=location.hash
if(hash){
var el=$('.'+hash.substr(1))
if(el)
el.scrollView();
}
in the onLoad. Here we use the fragment as a way to tell the page which element to go to.
http://jsfiddle.net/hWEpL/5/
This is the updated jsfiddle (with simulated hashed location being already followed using
location.href="#section-3" //simulate named links. do not include this in your code
Moving forward, perhaps semantically, you could use ID instead of class, to use the default behaviour of fragments if javascript is disabled, but then you have to place this piece of code to actually prevent the default behaviour (and allow the animation to occur) as stated in https://stackoverflow.com/a/3659116/1480215
setTimeout(function() {
if (location.hash) {
window.scrollTo(0, 0);
}
}, 1);

Categories