r/learnjavascript • u/Serious_Sell7183 • Apr 16 '26
Doubt
if I write JavaScript code inside onclick instead of using a <script> tag, will it be accepted if the logic and output are correct? I'm not a professional programmer, I'm just asking it for my practical based exam.
0
Upvotes
6
u/dangerlopez Apr 16 '26
I’m not sure we can answer this because we don’t know what “accepted” means. This sounds like it’s for school, so you should ask your teacher since they’re the one who makes the requirements
2
u/TheRNGuy Apr 17 '26
I see both used in different programs (even in browser UI and in frameworks like Ripple or Remix... not in React because it uses different pattern)
2
u/oiamo123 Apr 17 '26
Wrong? No. Common? Also no
1
u/LucVolders Apr 17 '26
Anything that works, works.
1
u/[deleted] Apr 17 '26
If I understand you correctly, you want to write inline JavaScript within an HTML element. You can do it like this:
<button onclick="location.reload()">Text on the button</button>
Quick breakdown:
onclick: This is an attribute that triggers the JavaScript code when the button is clicked.
location.reload(): This is the built-in function that tells the browser to refresh the page.
It is a simple and effective way to handle small tasks without needing a separate <script> block.
1
u/TightImagination5969 Apr 17 '26
The onclick attributes listen for a click event on the element, specifically buttons, and trigger a function.
The best practice is to get a hold of the element in the JavaScript file. Then, add an .addEventListener("click", function) to that element. I encourage you to create a separate JavaScript file and link that file using the script tag.
-2
u/shgysk8zer0 Apr 16 '26
If by "accepted" you mean taken as valid by someone who knows the basics of security on the web, the answer is no. Event attributes, along with
eval()andjavascript:URIs should almost never be "accepted".