0

HTML and JS code working on the app but not on web browser

Hi all, Can aynone tell me why the following code is working just fine on the sololearn app, but on sololearn for web browser (chrome), I am getting the following error: "ReferenceError: testing is not defined at HTMLButtonElement.onclick" HTML: <button id="test" onclick="testing()">Test</button> JS: function testing(){ document.getElementById('test').textContent = "the function is working"; } Thank you! Corentin

14th Feb 2022, 8:30 AM
Corentin Fleur
5 Answers
+ 2
Runs in app but not in browser? well this is the first time. It's more often people get to run their code in browser but got error in the app. Code looks okay though, maybe try to put the JS code in a script block after body?
14th Feb 2022, 10:01 AM
Ipang
+ 1
The complete code of your HTML would be better to help you.
14th Feb 2022, 8:39 AM
Geoffrey L
Geoffrey L - avatar
+ 1
The problem is that sololearn website wraps javascript in an IIFE (Immediately Invoked Function Expression) when it is written the javascript tab. So the function testing is hidden from the onclick eventhandler. One way resolve this problem is make testing() a function expression and a property of the Window object like so- window.testing = function() { your code...} Another way to resolve this is use addEventListener instead on onclick- document.getElementById('test').addEventListener('click',testing)
14th Feb 2022, 1:06 PM
ODLNT
ODLNT - avatar
0
Hi, I wrote this small test code to understand why my main code was not working, as I was getting the same error. There is nothing else more than the button on the test code: <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <button id="test" onclick="testing()">Test</button> </body> </html>
14th Feb 2022, 9:18 AM
Corentin Fleur
0
Inside your HTML you didn't declare your "testing" function so it's not aware of it. You can either link it has an external file inside the "head" tag but the best practice is to declare it at the end of the "body" tag. For example : <body> ...some HTML here... <button id="test".......> function testing() { .... } </body>
14th Feb 2022, 2:19 PM
Geoffrey L
Geoffrey L - avatar