So the structure of my handlebars template is below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{title}}</title>
{{> _meta_tags}}
{{> _styles}}
{{> _head_scripts}}
{{> _ga}}
</head>
<body>
<div class="content-wrap" id="content-wrap">
<div class="content" id="content">
{{> _thank_you}}
{{> _contact_form}}
{{> _header}}
{{{body}}}
{{> _footer}}
</div>
</div>
{{> _body_scripts}}
</body>
</html>
And the code I am testing is the following:
// page transitions
const content = document.querySelector('#content');
const about = document.querySelector('a[href="/about"]');
about.addEventListener('click', (e) => {
const parser = new DOMParser();
const parent = content.parentNode;
e.preventDefault();
anime({
targets: parent,
opacity: 0,
duration: 500,
complete: () => {
axios.get('/about')
.then((data) => {
parent.removeChild(content);
const doc = parser.parseFromString(data.data, 'text/html');
parent.appendChild(doc.querySelector('#content'));
}).then(anime({
targets: parent,
opacity: 1,
duration: 500,
}));
},
});
});
I am using broswerify to bundle the js and in the above code axios is an npm module that handles ajax requests.
Basically when then new content replaces the old content all the event handlers are unbound, and therefore all interactivity is lost. Is there a way to rebind everything in one go?
I realise that I should probably be using Angular or React to do this but I'm just going with what I know rather than digging into something else I don't know. This is basically a portfolio site so that I can learn stuff :)
I have looked all over for how to do this but everything I find is jQuery.
You should look at event delegation. In your case, you can bind events to the non-dynamic parent so that the event handlers aren't unbound when new child elements are added or some are replaced.
Why do you need to destruct whole your HTML?
Why do you use DOMParser?
Yes, of course, when you remove element from DOM you also removing listeners and when you adding new elements into DOM they don't have any listeners, however, you can MOVE elements in DOM and save attached listeners, but why do you need to attach event listeners on something you removed? You NEVER remove element from DOM if you need it. Just init() widgets you inserted into DOM later or use DOMObserver API to do so automatically.
So, answer to your main question is obvious - you have to attach event listeners exactly the same way you attached them first time.
However, I very appreciate that you are using vanilla JS and you may look into BunnyJS and join Gitter chat room where I would be able to provide your with some tips on how you may write simple and on the same time powerful, maintainable, modern code using nothing but plain JavaScript.