I need this javascript to run when the page is loaded:

document.body.innerHTML = document.body.innerHTML.replace(/\} \}/g, '}}');

I also need this jQuery to run when the page is loaded (handles my sidebar):

$('[data-toggle=offcanvas]').click(function() {
    $('.row-offcanvas').toggleClass('active');
});

This works for the sidebar (placed just before </body>):

<script>$(document).ready(function() {
  $('[data-toggle=offcanvas]').click(function() {
    $('.row-offcanvas').toggleClass('active');
  });
});</script>

But if I add the regex line like this:

<script>$(document).ready(function() {
  $('[data-toggle=offcanvas]').click(function() {
    $('.row-offcanvas').toggleClass('active');
  });
  document.body.innerHTML = document.body.innerHTML.replace(/\} \}/g, '}}');
});</script>

The regex works but the sidebar bit stops working. Is this because I'm mixing Javascript and jQuery? How would I fix this? Thanks.

share|improve this question
2  
This feels like an XY Problem. Why do you need to run that regex? That looks like some escaped JSON or similar, that may be better handled in another way.... – cale_b 47 mins ago
4  
No, it's because you're replacing the content of your page with new content. The new content doesn't have event handlers. This is not a good way of doing whatever you are trying to do. – Kevin B 47 mins ago
3  
"Is this because I'm mixing Javascript and jQuery?" jQuery is javascript. – Jonathan M 47 mins ago
1  
document.body.innerHTML = ... replaces everything in the body, removing event handlers and pretty much everything else – adeneo 46 mins ago
1  
@Garry, sounds like the site generator is expecting templating markup designated by double braces. You might be able to turn that off on the site generator. – Jonathan M 41 mins ago
up vote 0 down vote accepted

You are replacing the document body so your bindings are lost.

$(document).ready(function() {
  // change body
  document.body.innerHTML = document.body.innerHTML.replace(/\} \}/g, '}}');
  // then bind to new body
  $('[data-toggle=offcanvas]').click(function() {
    $('.row-offcanvas').toggleClass('active');
  });

});
share|improve this answer
    
Thank you so much. Works perfectly. – Garry 33 mins ago

Perhaps a cleaner method based on your clarifying comment that the only double braces you want to replace are in the elements with class my-content:

$('.my-content').text().replace(/\} \}/g, '}}');
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.