Anchor-Links jump to wrong place - javascript

I just can't figure out this problem.
The circumstances:
Website (Wordpress with Genesis and Altitude-Pro theme) with 4 pages with anchor-sections on it.
The problem:
If a link got clicked it loads the url with the hash (.../#section1) but it is not on the correct position. After hitting enter in the URL it jumps to the correct position.
I think this is because of Images that are loaded and the site jumps to the location before that.
What I tried:
I used this code, but it doesn change anything:
$( window ).load(function() {
alert("LOADED");
hash = document.location.hash;
alert(hash);
if (hash !="") {
setTimeout(function() {
if (location.hash) {
window.scrollTo(0, 0);
window.location.href = hash;
}
}, 1);
}
else {
return false;
}
});
Here's the link to the Demosite -> DEMOSITE

Related

Run JavaScript function only if you're refreshing the page or coming to the page from external link

We have a Lottie animation that should act as a preloader and show only on the Home page.
We want to SHOW this when accessing the home page by:
clicking on a link from an external page (not on your website)
clicking refresh on the browser
when entering the URL in the browser's address bar.
We DON'T want to show the animation when
clicking on a link from an internal page (on your website)
navigate through the browser's prev/next history buttons.
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>
<div id="preloader">
<div class="logo" id="home-preloader"></div>
</div>
<style>
/* Some styling here */
</style>
<script>
function playPreloader() {
var animation = bodymovin.loadAnimation({
container: document.getElementById('home-preloader'),
path: 'preloader.json',
renderer: 'svg',
loop: false,
autoplay: true,
name: "Home Preloader",
});
}
</script>
Any ideas on how to do it? I tried a few things with PerformanceNavigation.type and PerformanceNavigationTiming.type but couldn't manage to figure it out. I'm not very skilled in JavaScript, but can manage things if I can have direction.
Even if this worked, it doesn't seem to differentiate between external and internal links.
window.addEventListener("load", function() {
var performance = window.performance || window.webkitPerformance || window.msPerformance || window.mozPerformance;
var navigation = performance.getEntriesByType("navigation")[0];
if (navigation.type === "navigate") {
console.log("The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.");
}
else if (navigation.type === "reload") {
console.log("The page was accessed by clicking the Reload button or via the Location.reload() method.");
playPreloader();
yesPreloader();
}
else if (navigation.type === "back_forward") {
console.log("The page was accessed by navigating into the history.");
noPreloader();
}
else {
console.log("Any other way.");
}
});
After researching for two days, I found a comment that was very helpful and helped me create a working solution to my problem. Here's the code for anyone having the same problem.
If somebody can confirm that all of this is correct, that would be nice.
/* (0) WHEN THE PAGE IS LOADED */
window.addEventListener("load", function() {
/* (1) FIND HOW THE PAGE WAS ACCESSED */
var result;
var p;
if (window.performance.navigation) {
result = window.performance.navigation;
// 255
if (result == 255) {
result = 4
}
}
if (window.performance.getEntriesByType("navigation")) {
p = window.performance.getEntriesByType("navigation")[0].type;
// Page was accessed from a link or address bar
if (p == 'navigate') {
result = 0
}
// Page was reloaded (browser reload operation)
if (p == 'reload') {
result = 1
}
// Back or Forward (browser history)
if (p == 'back_forward') {
result = 2
}
// Prerender
if (p == 'prerender') {
result = 3
}
}
console.info(result);
/* (2) WHAT TO DO IN EACH CASE */
if (result == 0) {
// Page was accessed from a link or address bar
console.info("Page was accessed from a link or address bar");
console.info("Result was 0, result=" + result);
// Was it an internal link or (external link or address bar)
if (document.referrer.indexOf(location.hostname) !== -1) {
// Page was accessed from an internal link
console.info("Page was accessed from an internal link");
$(document).ready(function() {
noPreloader();
});
} else {
// Page was NOT accessed from internal link
// Probably accessed from external link or address bar
console.info("Page was NOT accessed from internal link. Probably accessed from an external link or address bar");
$(document).ready(function() {
$(this).scrollTop(0);
document.body.classList.add("overflow-x-hidden");
document.body.classList.add("overflow-y-hidden");
playPreloader();
yesPreloader();
});
}
} else if (result == 1) {
// Page was reloaded (browser reload operation)
console.info("Page was accessed by reloading (browser reload operation)");
console.info("Result was 1, result=" + result);
$(document).ready(function() {
$(this).scrollTop(0);
document.body.classList.add("overflow-x-hidden");
document.body.classList.add("overflow-y-hidden");
playPreloader();
yesPreloader();
});
} else if (result == 2) {
// Back or Forward (browser history)
console.info("Page was accessed from the browser history back or forward buttons");
console.info("Result was 2, result=" + result);
$(document).ready(function() {
noPreloader();
});
} else {
// Any other instance
console.info("Page was accessed: Any other instance (prerender or 255)");
console.info("Result was probably 255 (4) or prerender (3), result=" + result);
$(document).ready(function() {
noPreloader();
});
}
});
/* [END OF] (1) WHEN THE PAGE IS LOADED */

ajax image viewer , back button and history - missing html and css

I am playing with jquery and js, trying to build an ajax overlay image viewer for a PHP website. With this code included at the bottom of the 'gallery page', the viewer opens and i can navigate with next and previous links inside the viewer. But the back button and the history is hard to understand. The browser often shows only the response of the ajax call, without the underlying page and css files, after some clicks back.
Perhaps somebody knows what is generally happening in such a case? I would like to understand why back sometimes results in a broken page, i.e. only the ajax response.
<script type="text/javascript">
$(document).ready(function() {
function loadOverlay(href) {
$.ajax({
url: href,
})
.done(function( data ) {
var theoverlay = $('#flvr_overlay');
theoverlay.html( data );
var zoompic = $('#zoompic');
zoompic.load(function() {
var nih = zoompic.prop('naturalHeight');
var photobox = $('#photobox');
if($(window).width() >= 750){
photobox.css('height',nih);
}
theoverlay.show();
$('body').css('overflow-y','hidden');
$(window).resize(function () {
var viewportWidth = $(window).width();
if (viewportWidth < 750) {
photobox.css('height','auto');
zoompic.removeClass('translatecenter');
}else{
photobox.css('height',nih);
zoompic.addClass('translatecenter');
}
});
});
});
return false;
}
var inithref = window.location.href;
$(window).on('popstate', function (e) {
if (e.originalEvent.state !== null) {
//load next/previous
loadOverlay(location.href);
} else {
//close overlay
$('#flvr_overlay').hide().empty();
$('body').css('overflow-y','scroll');
history.replaceState(null, inithref, inithref);
}
});
$(document).on('click', '.overlay', function () {
var href = $(this).attr('href');
history.pushState({}, href, href);
loadOverlay(href);
return false;
});
});
</script>
edit
clicking forward works:
/photos (normal page)
/photos/123 (overlay with '/photos' below)
/locations/x (normal page)
/photos/567 (overlay with '/locations/x' below)
clicking back gives me the broken view at point 2.
Do you need to prevent the default behaviour in your popstate to prevent the browser from actually navigating back to the previous page?
you have to manage it by own code.
You have a few options.
Use localstorage to remember the last query
Use cookies (but don't)
Use the hash as you tried with document.location.hash = "last search" to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request.
I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible
Changing to document.location.hash = "latest search" didn't change anything.t.
This goes into the rest of the jQuery code:
// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}
// Save the search result table when leaving the page.
$(window).unload(function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var form = $("#myTable").html();
localStorage.setItem('myTable', form);
}
});
Another solution is that use INPUT fields to preserved while using back button. So, I do like that :
My page contains an input hidden like that :
Once ajax content is dynamicaly loaded, I backup content into my hidden field before displaying it:
function loadAlaxContent()
{
var xmlRequest = $.ajax({
//prepare ajax request
// ...
}).done( function(htmlData) {
// save content
$('#bfCache').val( $('#bfCache').val() + htmlData);
// display it
displayAjaxContent(htmlData);
});
}
And last thing to do is to test the hidden field value at page loading. If it contains something, that because the back button has been used, so, we just have to display it.
jQuery(document).ready(function($) {
htmlData = $('#bfCache').val();
if(htmlData)
displayAjaxContent( htmlData );
});

Page transitions, depending on URL

This code fades each page out, before going to the URL's destination. However, there are some instances where the user doesn't go to a new page, but goes to a PDF in the browser, or it opens the default mail application. On Safari it seems, if you go to an external site (www.twitter.com) and press the back button, the .wrapper is still faded out. (Perhaps a cache thing?)
function fadeAndGo(x) {
$(x).click(function (e) {
e.preventDefault();
var href = this.href;
$('.wrapper').fadeOut(function(){
window.location = href;
});
// $('.wrapper').delay()fadeIn();
});
}
fadeAndGo('a');
Is it possible to either:
Fade out, only if the URL does not contain 'PDF, mailto', or is an external link?
Fade in after a certain amount of time (it faded out, but faded back in after a couple of seconds, in case it was a PDF/mailto).
Try this:
function fadeAndGo(x) {
$(x).click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
if (!/PDF|mailto/gi.test(href)) {
$('.wrapper').fadeOut(function () {
window.location = href;
}).delay(2000).fadeIn();
} else {
window.location = href;
}
});
}
fadeAndGo('a');

If current page is X, do this action

I have a simple site, which slides the content off the page before taking you to the URL. However, I need to be able to determine the slide direction, depending on which page you're currently on.
I need to do this, but I'm not sure how to articulate it properly with jQuery:
if (current page == about.php) {
animate right then go to target URL }
else {
do default behaviour }
At the moment, I have this function which doesn't work well, because it animates in a certain way regardless of which URL you're going to:
function animateLeftAndGo(x) {
$(x).click(function (e) {
e.preventDefault();
var href = this.href;
$('.pop-up').fadeOut(function(){
$('.wrapper').animate({left: "+=150%"}, "slow", function(){
window.location = href;
});
});
});
}
Which is called by:
animateLeftAndGo('a.archive');
How can I set up an if statement that asks if the current URL is about.php?
In JavaScript use the location object: http://www.w3schools.com/jsref/obj_location.asp
if (location.pathname == '') {
}

Javascript: is it possible to return false on an anchor element but still update the url without any jerky movement?

In the code below when the anchor element is clicked I am trying to update the url with the anchor's 'href' and scroll down to the relevant 'id':
jQuery(document).ready(function($) {
(function() {
function update_url(id, url, scroll) {
this.id = id;
this.url = url;
this.scroll = scroll;
this.update();
}
update_url.prototype.update = function() {
var url = this.url;
$(this.id).click(function() {
var append = $(this).attr('href');
testing.scrollTo();
document.location.href = url + append;
return false;
});
}
update_url.prototype.scrollTo = function() {
$('html,body').animate({
scrollTop: $("#" + this.scroll).offset().top
},'slow');
}
var testing = new update_url('a', document.URL, 'people');
})(); });
The problem is when you click the anchor the return false; doesn't kick in quick enough so the page jerks for a second before scrolling down.
Is there a way of updating the page's url and still avoiding this jerky movement?
The problem is not that the return false; is triggered too late, but rather that the change you make to document.location.href causes the page reload no matter what.
HTML5 pushState is what you're looking for. If you're using HTML5, that is.
If not, you'll want to resort to hash navigation.
There's also a plugin for that, of course. It supports pushState as well as hash navigation - one less thing for you to worry about.

Categories

Resources