thymeleaf:external js file - javascript

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

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/

Related

Button in JavaScript is not working as expected

An error message appeared after adding my button which calls a function in JavaScript. I cannot find the problem.
Sorry for the faults. I am French and I'm using Google Translate.
Here is the part of the code in question:
document.getElementById("jouer").onclick = start();
document.getElementById("jouer").onclick = function () { alert('defis[0]'); };
<input id= "jouer " type="button" value="jouer" click="start()"/>;
And the error message is:
Uncaught SyntaxError: Unexpected token '<'
It seems like you are trying to run both JS and HTML in one file.
To get it to work, you need to create a separate file with HTML stuff and use
<script src="your-js-file.js"></script> in the HTML file for the browser to be able to run JS.
function start() {
alert('i am working')
};
document.getElementById('jouer2').onclick = start
<input id= "jouer " type="button" value="jouer" onclick="start()"/>;
<input id= "jouer2" type="button" value="jouer2"/>;
target.onclick = functionRef;
functionRef is a function name or a function expression. so you can try this
document.getElementById("jouer").onclick = start;
also you don't need the click attribute in the element as you are targeting the DOM element above. if you want to trigger a function directly from some element then pass onclick attribute with the function call and you won't need to target like this
document.getElementById("jouer").onclick
reference: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick
The only error i see is that you have a whitspace in the id selector in the input "jouer". this causes the script to not be able to grab the element. Otherwise, the error Uncaught SyntaxError: Unexpected token '<' means that you are trying to include a file (script) that it can't find.

check if my body tag has a class, in vanilla JS

I am trying to simply show/hide content; by creating an if statement in plain JS to detect if the current body tag has a specific class attached; i.e. home
I am trying the below; on the correct page, but am not getting the alert.
var elem = document.querySelector('body');
if (elem.classList.contains('test')) {
alert('test');
}
no jQuery!!
error with the above code is:
Uncaught TypeError: Cannot read property 'classList' of null
I just want this to run on page load
As long as you wait for the DOMContentLoaded event you should be golden.
Check out the tests below.
NOTE: Snippet engine is NOT a good test for this, the HTML is always ready :)
document.addEventListener('DOMContentLoaded', () => {
console.log(document.body.classList);
console.log(document.body.className);
if(document.body.classList.length > 0) {
console.log(document.body.className);
}
});
<body class="testing test2">
<p>Hello world</p>
</body>

Catch22 - HTML waiting for JS, JS waiting for HTML

I'm a newbie trying to write a JS/HTML report generator based on criteria which I submit in an HTML form. The plan eventually is to use PHP/mySQL to manipulate a database and return results but for now I'm just trying to build the HTML/CSS/JS and I've got stuck. I have attributed a JS function to a button in the <body> like so:
<input type="button" id="reportButton" value="Generate Report" onclick="showCriteria()">
I included a script in the <head> as follows:
<script>var showCriteria = function(){ My JS code...}</script>.
This function simply does some date manipulation and displays the result in a div on the same page like so:
document.getElementById("endDate").innerHTML = "to "+endDay+" "+endMonthName+" "+endYear;
But I get Uncaught TypeError: Cannot set property 'innerHTML' of null. So I searched the forum and discovered that this can sometimes be caused by not waiting for the window to load. So I wrapped the script as follows:
<script>
window.onload = function()
var showCriteria = function(){ My JS code...}
That solved the initial error but I then get Uncaught ReferenceError: showCriteria is not defined
It seems like I'm in a Catch22. I get the first error because the script is running before the window has loaded. I fix that by waiting for the window to load only to find that the HTML is waiting for my script to define my JS function.
Any advice gratefully received.
Report Generator screenshot
Window.load script
You've almost got the solution. At least you've got all the right elements.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};
This will make it so the button does not function until the page is ready.
You also need to remove the onclick from the button.
When you put the showCriteria function inside window.onload, please make sure it is accessible by the DOM, i.e. window.showCriteria.
<script>
window.onload = function()
window.showCriteria = function(){ My JS code...}
...
Beside using onclick on html, you can use add listener to listen the click event on that element.
window.onload = function() {
document.getElementById('reportButton').addEventListener('click', showCriteria);
};

Why am I getting "Uncaught TypeError: download is not a function"

download
<script type="text/javascript">
function download() {
alert("hello");
}
</script>
When I click the link, I don't see an alert. Instead it says the function doesn't exist. Why?
When I rename download to downloadx, it still doesn't work, so it's not the name of my function that's a problem.
First of all as #gmo said your code will never work outside JSFiddle because of the name of the function.
Read More about it HERE (Can't use “download” as a function name in javascript)
From now on i'll use downloadx as the function's name
Instead another problem caused by JSFiddle makes your code non functioning even if you use downloadx.
simple-example-doesnt-work-on-jsfiddle
JSfiddle wrap your code inside a window.onload function, so the download function is outside of the scope.
//<![CDATA[
window.onload=function(){
function downloadx() {
alert("hello");
}
}//]]>
SOLUTION 1 JSFiddle
you should declare it directly on window
window.downloadx = function() {
alert("hello");
}
SOLUTION 2 JSFiddle
Select No wrap - in <head>
On the left column in JSFiddle
NB
In any case you should use another name for the function, this is the reason why it doesn't work outside JSFiddle.
I still think it's a duplicate question from here: Can't use "download" as a function name in javascript
And related exclusive on the function name in a tag.
...<a> elements have a download attribute in HTML5 as explained
here...
Maybe a workaround is possible, but definitely not recommendable to mess with browser native functions.
But.. if you still think that it's not.. please try this:
(no hacks needed)
function download() {
alert("hello");
}
function downloadx() {
alert("hello");
}
download <-- not working
<br />
downloadx <-- works
<br />
<span onClick="download();">download</span> <-- works
The last one use download as function name and also work, why?
Because it's not an <a> tag.

Add a button which calls a Content script function on click?

I have the follwing code in the content.js of Google Chrome extension:
jQuery(document).ready(function () {
jQuery("body").html('<input type="button" id="soso" value="asd" onclick="goFrame()" />');
});
function goFrame() {
alert('Value');
}
The button is created successfully, but when I click on it the message doesn't appear and I got the follwing error in the Google Chrome console:
Uncaught ReferenceError: goFrame is not defined
First read Chrome extension code vs Content scripts vs Injected scripts.
To solve the problem, get rid off the inline event listener, and bind the event dynamically:
...
var $input = $('<input type="button" id="soso" value="asd">').click(goFrame);
jQuery("body").html($input);
});
function goFrame() {
alert('Value');
}

Categories

Resources