1

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

Ronnie147
  • 39
  • 3
  • 8
  • 1
    seems like the change2 function is firing before the external script completely loads. you could use an onload handler to call change2 to fix it. see this: http://stackoverflow.com/questions/3842614/how-do-i-call-a-javascript-function-on-page-load – Rooster Jul 15 '14 at 15:09

1 Answers1

1

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/

Nickey
  • 1,191
  • 1
  • 13
  • 21
  • thanks!it seems that the whole problem was the document.getElementById("l1").setAttribute("class", "");with removal even my code worked.so is there another way to make an element to have no class? – Ronnie147 Jul 17 '14 at 04:08
  • I didn't quite understood your question but, if there isn't an element with id= "I1" in the dom, then this document.getElementById("l1") will return null and document.getElementById("l1").setAttribute("class", ""); will be an invalid command. Before you remove an element's class you should check for that element's existence in the dom. Also one minor comment is that class should be removed in this way http://stackoverflow.com/a/2155786/3414905 in order to avoid removing other classes, this element might have. – Nickey Jul 17 '14 at 07:37