Ronnie147
Ronnie147

Reputation: 39

thymeleaf:external js file

i'm trying to use an external javascript file in a thymeleaf project so i've done the following:

this is how the file is declared(i put this just before /body as suggested in many other posts)

<script type="text/javascript" th:src="@{/resources/lor.js}"></script>

this is the html function call

<a id="l2" th:href="'javascript:change2();'">

and this is the js file

function change1() {
 document.getElementById("l1").setAttribute("class", "selected");
 document.getElementById("l2").setAttribute("class", "");

};


function change2() {

 document.getElementById("l1").setAttribute("class", "");
 document.getElementById("l2").setAttribute("class", "selected");

};

however i get the following error "Uncaught ReferenceError: change2 is not defined" from firebug.

i've also tried

function change2() {

document.getElementById("l1").className="";
document.getElementById("l2").className="selected";

};

and i'm getting "Uncaught TypeError: Cannot set property 'className' of null"

it seems like the js file is not even processed.any solution?

thanks in advance

Upvotes: 1

Views: 2880

Answers (1)

Nickey
Nickey

Reputation: 1381

I would suggest that you used an event handler instead of a function call on the href attribute. So you may change your anchor link to this:

<a id="l2" href="javascript:void(0);">l2_Link</a>

To add a click event, you have to make use of the window.onload event as Rooster proposed.

window.onload = function (){
    document.getElementById ("l2").addEventListener ("click", change2, false);
}

You can view a working example of this at: http://jsfiddle.net/RKSZ2/1/

Upvotes: 1

Related Questions