Gemtastic
Gemtastic

Reputation: 6433

JavaScript won't run, says element is null, but code runs in fiddle

I'm building a thymeleaf and spring project with the java configuration. When I try out this code in a jsfiiddle it works fine, but when I try to run it in my application I get this: TypeError: document.getElementById(...) is null.

There is nothing wrong in the imports of the javascrips and the source renders them and the html just fine.

The code:

HTML:

<a href="#" id="buybutton" th:id="buybutton" th:text="#{cart.buy}">Buy</a>

JavaScript:

document.getElementById('buybutton').addEventListener("click", function(e){
   console.log("bought"); 
});

Thymeleaf configuration (if it is of any importance):

@Configuration
public class ThymeleafConfig {

@Bean
public ServletContextTemplateResolver templateResolver() {
    ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
    resolver.setPrefix("/WEB-INF/pages/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode("HTML5");
    resolver.setOrder(1);
            resolver.setCacheable(false);
            resolver.setCharacterEncoding("UTF-8");

    return resolver;
}

}

Upvotes: 0

Views: 245

Answers (1)

Kelsadita
Kelsadita

Reputation: 1038

You should add click event only when the DOM is ready.

NOTE: In the case of jsfiddle this is default behaviour.

document.addEventListener("DOMContentLoaded", function(event) { 
  document.getElementById('buybutton').addEventListener("click", function(e){
   console.log("bought"); 
  });
});

Upvotes: 2

Related Questions