Hi there
I was thinking up of ways to get some fancy ajax page loads in kirby after seeing nodebb and after trying some solutions with kirby’s ajax, found out pjax.
From github:
pjax works by grabbing html from your server via ajax and replacing the content of a container on your page with the ajax’d html.
That’s what i meant by “quick and dirty”. This is not a real json request or anything, we’re still requesting the html. But in style.
What we need
Request pjax.js and nprogress.js for loading and status indication.
Add nprogress’s css.
Define in your html body what is your content container.
Initialize the jQuery and do some css fixes.
Step 1
Put the .js on your header
Github link for pjax.js
Github link for nprogress.js
<?php echo js('assets/js/jquery.pjax.js') ?>
<?php echo js('assets/js/nprogress.js') ?>
I’m assuming you are already requesting jQuery on your template. If not, let’s do that too.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Step 2
Add nprogress’s css to your css.
Github link to nprogress.css
Step 3
Add id="pjax-container"
to your main content.
Step 4
Now comes the dirty.
I’ve tried documenting what is going on directly on the code.
<script type="text/javascript">
$(function () {
function menuActive() { // Function to toggle active menu links
$('.active').removeClass('active'); // Remove "active" class on menu links after an ajax call
var pgurl = window.location.href; // Get the page url
// var pguri = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
// "uri" gets only the link folder while "url" gets the entire link
// Left here in case anyone out there uses $p->uri() on the menu
$(".menu a").each(function () {
if ($(this).attr("href") == pgurl || $(this).attr("href") == '') { // Compare url to links
$(this).addClass("active"); // Set "active" class on menu links
$(this).parents('li').children('a').addClass('active'); // Set "active" class on the parent of submenu links
}
});
}
// Requires jQuery 1.7+ to utilize the new "on" event attachment
$("body").on("click", "a", function (event) {
$.pjax({
"url": $(this).attr("href"),
"fragment": "#pjax-container",
"container": "#pjax-container",
"complete": function (data) { // Want to do something else? Left here for reasons
}
});
event.preventDefault();
});
$(document).on('pjax:start', function () {
NProgress.start(); // Start the nprogress bar
});
$(document).on('pjax:end', function () {
NProgress.done(); // End the nprogress bar
menuActive(); // Update the "active" class on links after ajax call
});
$(document).ready(menuActive); // Update the "active" class on links on first load
});
</script>
Aaaaand we’re done.
Check out a vanilla kirby installation example.
Also, it was done this way because I thought the normal method was bit complicated, having to create new templates and defining what fields would be passed along.
This allows you to keep your current templates.
cheers!