$(document).ready(initializeLazyContentLoading); function prepareLazyLinks() { // iterate over all a-links // if pageTarget attribute is set, prepare link for lazy loading $.each( $('a'), function (key, value) { if ($(value).attr('pageTarget') !== undefined) { var pageTarget = $(value).attr('pageTarget'); // link leads to # + base64 of page target $(value).attr('href', '#' + btoa(pageTarget)); $(value).click(function () { // clear old content if (window.location.hash.slice(1) != btoa(pageTarget)) $('main').text(''); return true; }); } }); } function prepareLazyForms() { // prepare all forms $.each( $('form'), function (key, value) { if ($(value).attr('actionTarget') !== undefined) { var actionTarget = $(value).attr('actionTarget'); $(value).submit(function (event) { lazyPostForm(actionTarget, value); event.preventDefault(); }); } }); } function initializeLazyContentLoading() { prepareLazyLinks(); // watch changes in the location hashtag setTimeout(lazyContentLoadingTimer, 100); prepareLazyForms(); } function lazyLoadPage(pageTarget) { $('main').load('lazy.php?page=' + pageTarget, function () { // there may be new lazy links / forms in the loaded content, so re-prepare everything prepareLazyLinks(); prepareLazyForms(); }); updateActiveNavbarItem(pageTarget); } function lazyPostForm(actionTarget, form, targetID) { $.post('lazy.php?page=' + actionTarget, $(form).serialize()).done(function (data) { if (targetID !== undefined) { $('#' + targetID).html(data); } else { $('main').html(data); } // there may be new lazy links / forms in the loaded content, so re-prepare everything prepareLazyLinks(); prepareLazyForms(); }); } function updateActiveNavbarItem(pageTarget) { if (pageTarget == "") return; $.each( $('li'), function (key, value) { if ($(value).attr('activeOnPage') !== undefined) { if ($(value).attr('activeOnPage') == pageTarget) { $(value).addClass('active'); } else { $(value).removeClass('active'); } } }); } function lazyContentLoadingTimer() { if (lazyContentLoadingTimer.lastHash === undefined) { lazyContentLoadingTimer.lastHash = window.location.hash; } if (window.location.hash != lazyContentLoadingTimer.lastHash) { lazyContentLoadingTimer.lastHash = window.location.hash; lazyLoadPage(atob(window.location.hash.slice(1))); } setTimeout(lazyContentLoadingTimer, 100); }