Adding attributes to elements that won't be re-rendered on navigation (body, header, etc)

Preface

By default your changes are cleared when the page reload. 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 be cleared)

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

Important! 

Make sure you've added the keyword /* sg_no_proxy */ first in your code. See further information.

 

Adding attributes to elements that won't be re-rendered on navigation (body, header, etc)

If you for example add a class to body or some other element that won't be reloaded / changed on navigation you need to start with removing this class before you set it. Otherwise this class will still be there after navigation.

  • Remove attributes before you add them

In the example below, we toggle a class when the user clicks on the cart container to show/hide the cart content. If the user does not close this and navigates the cart would still be open on the new page as well because the class isn't removed.

Example:

Wrong way - this class will still be there after navigation even though you haven't closed the cart because it's added to body that isn't re-rendered.

$("body").on("click", ".sg-cart-container", function(){
    $("body").toggleClass("sg-show-cart");
});


Right way
- Always remove the attribute before you add it

Notice that we also remove the event handler before we set it to avoid duplicates. Read more on how to Remove / undo changes on Audience false

$("body").removeClass("sg-show-cart");
//remove the event handler before adding it to prevent duplicates
$("body").off("click", ".sg-cart-container");

$("body").on("click", ".sg-cart-container", function(){
    $("body").toggleClass("sg-show-cart");
});

 

Was this article helpful?
0 out of 0 found this helpful