My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

How do I rebind events to my page after loading in new content via ajax?

John Enderby's photo
John Enderby
·Mar 10, 2017

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.