-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?

4
  • Provide some code sample. Commented Mar 10, 2018 at 18:38
  • Possible duplicate of How to use external ".js" files Commented Mar 10, 2018 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: <button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button> Commented Mar 10, 2018 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. Commented Mar 10, 2018 at 18:42

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.