How to keep elements non-refreshed
From what you said I think I might have found the solution you're looking for - you want to load content dynamically whilst keeping the logo and navigation untouched? If so, this might be what you're looking for.
In the example, the pages are loaded in from a div within the page but could be used to load another URL or file:
$('.viewport ul li a').on('click', function(e) { e.preventDefault(); var link = this.hash.substring(1, this.hash.length); if($('.'+link).length) { $('.viewport span.body').html($('.'+link).html()); }});
TL;DR
I've created a plunker for you, take a look, and play with it as long as you can. You'll learn a lot from it!
I think you're trying too many things here, but didn't try the simplest:
The main goal is to keep non-refreshed the logotext and the menu ,without clipping on page refresh or while the content is loading from a page to another. Also the menu state should be preserved from a page to another.
If you want to do that, there are a few steps:
- Create a 'master' page, that we're going to call
index.html
from now on. - So, our index must have the static part of our page, e.g menu, logo, footer etc.
- Then, our 'subpages' must be cut down (no
html
,head
,body
,script
,style
tags, only the content that should be showed into our master page). That done, now we must change our links to use AJAX instead of doing full refresh:
/* we add a 'click' event handler to our menu */document.getElementById('menu-menu-2').addEventListener('click', function(e) { var el = e.target; /* then, we see if the element that was clicked is a anchor */ if (el.tagName === 'A') { /* we prevent the default functionality of the anchor (i.e redirect to the page) */ e.preventDefault(); /* we show our spinner, so the user can see that something is loading */ spinner.classList.remove('hidden'); /* and we call our AJAX function, passing a function as the callback */ ajax(el.href, function(xhr) { /* we get our main div, and we replace its HTML to the response that came from the AJAX request */ document.getElementById('main').innerHTML = xhr.responseText; /* since the request was finished, we hide our spinner again */ spinner.classList.add('hidden'); }); }});
Ok, now our pages are already working via AJAX, and not reloading our static content.
But now, we see that we have some issues. For example, if someone tries to open one of our pages directly via URL, he'll see unstyled page, without the menu/logo etc. So, what should we do?
We have a few more steps now:
Simulate that our links are effectively transfering between pages using the History API:
/* inside our ajax callback, we save the fake-redirect we made into the pushState */ajax(el.href, function(xhr) { document.getElementById('main').innerHTML = xhr.responseText; /* save the new html, so when the user uses the back button, we can load it again */ history.pushState({ html: main.innerHTML, title: el.textContent + '| neuegrid' }, '', el.href); /* (...) */});/* and outside it, we add a 'popstate' event handler */window.addEventListener('popstate', function(e) { /* so, if we've saved the state before, we can restore it now */ if (e.state) { document.getElementById('main').innerHTML = e.state.html; document.title = e.state.title; }});
And we need that when the user enters directly to another page, e.g
about-us
, we redirect him to theindex.html
, and then load theabout-us
page from there.So we create a
redirect.js
file, and we reference it in all of oursubpages:/* save the page that the user tried to load into the sessionStorage */sessionStorage.setItem('page', location.pathname);/* and them, we redirect him to our main page */location.replace('/');
And then, in our
index.html
page, we see if there is any page in thesessionStorage
, and we load it, if there is, otherwise we load ourhome
page.var page = sessionStorage.getItem('page') || 'home';/* we look into the menu items, and find which has an href attribute ending with the page's URL we wanna load */document.querySelector('#menu-menu-2 > li > a[href$="' + page + '"').click();
And that's it, we're done now. Take a look at the plunker I've been making to you.
And play with it as long as you can, so you'll learn a lot from it.
I hope I could help you! :)
Note: Just for reference, this is our ajax
function:
function ajax(url, callback, method, params) { if (!method) method = 'GET'; var xhr = new XMLHttpRequest(); xhr.open(method, url); if (callback) xhr.addEventListener('load', function() { callback.call(this, xhr); }); if (params) { params = Object.keys(params).map(function(key) { return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); }).join('&'); xhr.send(params); } else { xhr.send(); }}
GOING AJAXED WITH WORDPRESS
follow these simple steps (let's take as example theme "twentyfifteen"
on the WP templates folder):
- edit
single.php
,page.php
,index.php
and all other pages havingget_header()
andget_footer()
functions and replace it respectively with below code:
NOTE: this is important because if someone (ex: search-engine) reach your pages directly from the link, it is still fully available and 100% working. (useful for SEO)
<?php //get_header()if(!isset($_REQUEST['ajax'])){ get_header();}?><!-- other code ---><?php//get_footer()if(!isset($_REQUEST['ajax'])){ get_footer();}?>
- open the
header.php
add the below code inside the<head>
section at the very end
<script>!(function($) { $(function() { $('.menu-item a, .widget-area a, .page_item a').on('click', function(e) { e.preventDefault(); var href = this.href; var query = href ? (href + (!/\?/g.test(href) ? '?' : '&') + 'ajax=1') : window.location; /* IMPLEMENT SOME LOGIG HERE BEFORE PAGE LOAD */ /* ex: kill instance of running plugins */ $('#content').hide().empty().load(query, function() { /* IMPLEMENT SOME LOGIG HERE AFTER PAGE IS LOADED */ /* ex: refresh or run a new plugin instance for this page */ jQuery(this).show(); }); }); });})(jQuery); </script>
- in the
header.php
file put the code below at the end of the file, 90% of times you need it under the navigation. In this case we already have this on the"twentyfifteen"
theme.NB: most probably you have the opening tag
<div id="content" class="site-content">
inside theheader.php
file and the closing tag</div>
on thefooter.php
file, this doesn't matter, you can leave it as is.
<div id="content"></div>
NOTE: consider this a proof of concept; it may work as is, but you still need to tailor it to suit your needs; you may need to:
- Add a menu (in case it is not already set) by going under
Appeareace > Menus > [check Primary Menu] > Save Menu
in order to activate the menu. it's tested and working. - You may want to add some other class to the jQuery function like
.widget-area a
in order to ajax also widget links. - if you are using 3d party plugins you may need to ensure that all dependencies of each plugin are loaded also on the main page from where you want everything is displayed without refreshing content.
- you may need to check and kill those 3d party plugin before a new page load and run or refresh plugin needed in the loaded page.
- Add a menu (in case it is not already set) by going under