Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-4turbolinkshighlight.js

Turbolinks, limit javascript to one page


I am using highlight.js and applying this code to initialise the syntax highlighting for my code snippets on a blog app.

The following code is on my index.html page :

<script>
$(document).on('ready page:load', function() {
  $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
});
</script>

A code snippet should look like this originally:

<pre><code>A
B</code></pre>

And after applying the new style it turns into this:

<pre><code class=" hljs">A
B</code></pre>

The problem is that when I try to edit one of those posts on the edit.html page, in the editor I get the stylized version instead of the plain one, which I do not want. I want the new styles to be applied only to the index page. How can I make that happen?

I should mention I have generated a scaffold with all the included views: index, new, edit etc.

Also I have the jquery-turbolinks gem installed.

The problem goes this way: I load index.html and I get highlighted code. I navigate to edit.html and get highlighted code. I refresh the edit.html page and lose the highlight (which is how it should be).

--------------------------------------------EDIT-------------------------------------

Tried this and it did not work:

in my aplication.html.erb: <body data-action="<%= action_name %>" data-controller="<%= controller_name %>">

in my index.html.erb

<script>
    var data = $('body').data();
    if (data.controller === 'posts' && data.action != 'edit'){
        $(document).on('ready page:load', function() {
            $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
        });
    };
</script>

Solution

  • <body data-action="<%= action_name %>" data-controller="<%= controller_name %>">
    

    You can then read this in your script:

    $(document).on('page:change', function(){
        var data = $('body').data();
        if (data.controller === 'foo' && data.action === 'bar'){
    
        };
    });