Inline script works, I just need to use onclick='document.getElementById("").innerHTML
However, I cannot get it to work in an external file. Do I need to define an onclick function -- something already preset in HTML5?
Inline script works, I just need to use onclick='document.getElementById("").innerHTML
However, I cannot get it to work in an external file. Do I need to define an onclick function -- something already preset in HTML5?
Here a simple way of how it could be done:
external.js:
function myFancyOnClickHandler() {
document.getElementById('something').innerHTML = 'something'
}
index.html:
<!DOCTYPE HTML>
<html>
<head>
<script src="external.js"></script>
</head>
<body>
<div id="something" onclick="myFancyOnClickHandler()">Hello, World</div>
</body>
</html>
It's also possible to dynamically add an event listener with addEventListener
like this (this way you don't need the onload=""
attribute):
function myFancyOnClickHandler() {
document.getElementById('something').innerHTML = 'something'
}
// This only works IFF the element is present in the DOM
document.getElementById('something').addEventListener('click', myFancyOnClickHandler)
We can listen to the window
's load
or DOMContentLoaded
event to be sure the DOM has loaded:
function myFancyOnClickHandler() {
document.getElementById('something').innerHTML = 'something'
}
// This will work regardless of where we include the .js file
window.addEventListener('load', function() {
var elem = document.getElementById('something')
elem.addEventListener('click', myFancyOnClickHandler)
})
If you want to define the event handler in an external js file, this is the syntax:
document.getElementById("myBtn").addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello World";
});
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
Where 'myBtn' is an id you can assign in html