-3

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?

Matthew
  • 91
  • 3
  • 10
  • Provide some code sample. – baeyun Mar 10 '18 at 18:38
  • Possible duplicate of [How to use external ".js" files](https://stackoverflow.com/questions/11498068/how-to-use-external-js-files) – Tostifrosti Mar 10 '18 at 18:41
  • My first attempt at putting the code in didn't work. I'm simply trying to put W3 schools inline code into an external file: – Matthew Mar 10 '18 at 18:41
  • This is probably related to page load order. If your external script loads before the element exists, it will throw an error. Either wrap your code in a DOMContentLoaded handler or put the script tag after the element that it uses. – James Mar 10 '18 at 18:42

2 Answers2

1

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)
})
Marco
  • 7,007
  • 2
  • 19
  • 49
1

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

DannyMoshe
  • 6,023
  • 4
  • 31
  • 53