Arun Palanisamy
Arun Palanisamy

Reputation: 5459

Javascript not working in Thymeleaf file when making it as dynamic Page

I'm very new to thymeleaf and spring.This is the code i'm using. This javascript is not working in the code. Can somebody tell me what would be the problem.? Please correct me if i'm using wrong thymeleaf references.

    <script th:inline="javascript">
            //<![CDATA[
                    // Javascript to enable link to tab
                    var hash = document.location.hash;
                    var prefix = "tab_";
                    if (hash) {
                        $('.nav-tabs a[href=' + hash.replace(prefix, "") + ']').tab('show');
                    }

                    // Change hash for page-reload
                    $('.nav-tabs a').on('shown', function(e) {
                        window.location.hash = e.target.hash.replace("#", "#" + prefix);
                    });
                  //]]> 
                </script>  
            <script th:inline="javascript">
          //<![CDATA[
            $("#example-advanced").treetable({ expandable: true });

              // Highlight selected row
              $("#example-advanced tbody").on("mousedown", "tr", function() {
                $(".selected").not(this).removeClass("selected");
                $(this).toggleClass("selected");
              });


        //]]> 
            </script>   

This is working in Static page. But when making dynamic, it is not working as expected.

Upvotes: 1

Views: 6539

Answers (2)

Ostap Gonchar
Ostap Gonchar

Reputation: 782

Crazeaboutlife, what exaclty is not working?

Using Thymeleaf special syntax the text /<![CDATA[ will not disappear from the dynamical page. The point of inlining is to allow you to use special syntax for dynamic processing: /*[[...]]*/

For example If i have in my messages:

page.home.header=Page

Then i the following code:

<script th:inline="javascript">
  //<![CDATA[
    var heder = /*[[${page.home.header}]]*/'Static';
  //]]> 
</script>

Will be processed to:

<script th:inline="javascript">
  //<![CDATA[
    var heder = 'Page';
  //]]> 
</script>

Hope that clears you things out :)

Upvotes: 1

Beri
Beri

Reputation: 11600

Try surrounding it in :

 $(document).ready(function(){  /*Place your code here*/ })

Most common mistake- you are declaring JS when document may not yet had been loaded.

Second option, without more JS code, would be to add defer attribute to script tag, it will tell the browser to run the script only after all DOM is loaded.

Some more knowledge you can find here: How exactly does <script defer="defer"> work?

Upvotes: 0

Related Questions