Here is my website: https://memsmosaics.com/
I'm trying to make my website a single page website. When the website initally loads at index.html, it works as intended. At this time bottom section is loaded in nicely from gallery.html by the following function:
<script>
$(document).ready(function() {
$('#js-content').load('/gallery.html');
$('#js-navigation a').click(function(e) {
e.preventDefault();
$("#js-content").load(e.target.href);
})
});
</script>
When I navigate to the about section, and then return back to the home section by clicking on 'memsmosaics' in the top left, the gallery section no longer works as it should. It looks like the javascript is no longer applied to do things it was doing before - like aligning the images, and filtering by 'sold' and 'for sale'.
I have tried moving the relevant script tags from index.html to gallery.html, but this hasn't solved the problem. I'm not sure what else to try.
Thanks for any help!
You could listen for a popstate event after load, like this:
const initGallery = () => {
if(location.hash === '#new-section' || location.path === '/') {
$('#js-content').load('/gallery.html');
$('#js-navigation a').click(function(e) {
e.preventDefault();
$("#js-content").load(e.target.href);
})
}
}
window.addEventListener('popstate', initGallery)
$(document).ready(initGallery);
That is triggered during navigation. Here's an article that provides a bit more insight: https://gomakethings.com/how-to-detect-when-the-browser-url-changes-with-vanilla-js/
Edit with explanation: The problem you're running into is your handlers are being added only on load, so when the gallery is removed, you have detached DOM nodes hanging around, and they're never re-attached because the load event only fires on the initial page load. This creates a memory leak.
You can learn more about detached DOM nodes here: https://www.tutorialspoint.com/how-can-detached-dom-elements-cause-memory-leak-in-javascript
You could update the code above to remove the click listener. I'm not too familiar with jQuery, but the docs demonstrate an off
method, so your updated code could look like this alternatively:
const initGallery = () => {
const onClick = (e) => {
e.preventDefault();
$("#js-content").load(e.target.href);
}
const btn = $('js-navigation a')
if(location.hash === '#new-section' || location.path === '/') {
$('#js-content').load('/gallery.html');
btn.click(onClick)
return
}
if(btn) {
btn.off('click', onClick)
}
}
This should work, per the definition of popstate
:
When the transition occurs, either due to the user triggering the browser's "Back" button or otherwise, the popstate event is near the end of the process to transition to the new location.