Using event handlers on dynamic websites


By default, your changes are cleared when the page reloads. You get a "clean slate" for your code every time the visitor navigates. On dynamic websites a reload of the page is never done because new content is fetched dynamically. This can cause issues if you do changes on elements that do not refresh (header, footer, added attributes on <body>, etc.).

This can cause;

  • Duplications of your added functions
  • Duplications of your added elements
  • Added elements and attributes that still exist after navigation
  • Intervals and timeouts that keep running after navigation (if they haven't been cleared)

You will, in other words, have to handle this manually. Below we will show examples of how to do this.


Adding an event handler

Because the page is never reloaded your event handlers are never cleared/removed. This will cause them to be set over and over again when Audience (re-)evaluates to true and your code is run (on new content load/navigation).

The easiest way to handle this is to add a class to the element that you add the Event listener to, this way you can check if the class already exists (i.e the listener is already set) before you add the listener and avoid duplicated Event listeners. 

if(document.querySelector('.sg-event-set') === null) {
   // add Class
   let sg_buy_btn = document.querySelector('.buy-btn');
   // Event handler
   function sg_click_handler() {
      // code for click event

   // add Event listener
   sg_buy_btn.addEventListener('click', sg_click_handler);

You can remove this listener by passing the Event handler name. This way you do not remove any other listener that might be attached to the element. Remember to remove the class as well.

// remove event listener
let sg_buy_button = document.querySelector('.buy-btn');
sg_buy_button.removeEventListener('click', sg_click_handler);
Was this article helpful?
0 out of 0 found this helpful