0

At the very basic level, I understand that in-line javascript is the following:

<script>prompt()</script>

And this does not count as in-line javascript:

<script src="foo.com/bar.js"></script>

However, there's also other places where javascript can live, such as:

<button onclick="prompt()">
<form onsubmit="prompt()">
<img onerror="prompt()">
<style>{something "property":"javascript:prompt()"}</style>

Do all the other places that javascript live also count as in-line javascript?

What is the work-around for this? Inline Event handlers are also a bad practice

According to this reference, I would have to register event handlers before the closing body. Eg. I would assign each element on the page a specific ID, and AddEventListener on each element.

To make sure that I understand the idea, suppose I have a form - before the end of the body, I would include a javascript file that adds an event listener, so that my HTML would look like this:

<body>
<form id="theForm" name="theForm" method="POST"></form>
<script src="eventlisteners.js"></script>
</body>

And eventlisteners.js would like this:

var frm = document.getElementById("theForm");
frm.addEventListener('submit', console.log('foo'))

Is this correct? Is it also correct to say that every HTML inline event listener has a corresponding addEventListener argument?

appills
  • 172
  • 1
  • 14
  • You can assign event listeners to elements based on class names as well using `document.getElementsByClassName()`, which may be more suitable in some cases rather than doing this for each ID. – Adam Chubbuck Sep 04 '18 at 15:17
  • "*I would have to register event handlers before the closing body*" - no, you can register them from anywhere at any time (assuming that the DOM element exists already, you can't select it before it got parsed). Putting a ` – Bergi Sep 04 '18 at 15:20
  • "*every HTML inline event listener has a corresponding addEventListener argument?*" - not exactly, inline event listeners correspond to the [old `element.onclick = listener` model](https://quirksmode.org/js/events_tradmod.html) – Bergi Sep 04 '18 at 15:22

0 Answers0