0

I want to call a Java Script function inside following Thymeleaf and HTML code

<a class='btn btn-default btn-xs' href='#' role='button' th:id="view-notification">
  View Notification
</a>
<a href="index.php?cat=notifications">
  Notifications
  <span class="badge" th:id="notification-badge">1</span>
</a>

This is my Java Script function which I have properly included (I hope so) in my html file

<th:block th:fragment="scripts">
  <script th:inline="javascript">
    $('#view-notification').click(function () {
      $('#notification-badge').hide();
    });
  </script>

I inspected the html page and saw that js is not loading. What is wrong with my code?

4
  • 1
    That Javascript seems to use jQuery, did you include that as well? Commented Sep 28, 2017 at 4:55
  • Also Javascript is not Java! Commented Sep 28, 2017 at 4:56
  • What do you mean by "js is not loading"? If you view the page source, can you see your <script> block? Commented Sep 28, 2017 at 5:03
  • @UsagiMiyamoto yes, but Thymeleaf is Commented Sep 28, 2017 at 5:03

1 Answer 1

2

Is the script code below the button inside the html? Otherwise the script fails to register listeners. My guess it that the time the script is run, the button is not yet there. You could try to wrap the script inside the ready function.

$(document).ready(function() {
   $('#view-notification').click(function () {
       $('#notification-badge').hide();
   });
});

Another solution would be to set the listener on window and listen for clicks on the ID. This would even work you later chnge the code and render the button with an ajax call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.