0

I'm writing a Javascript library to monitor how the user interacts with form fields. It will have to monitor multiple events for a given element, so I can't use an onblah handler.

I would like the HTML author to decide what fields are monitored. I thought I'd offer something like this:

<script src="formWatch.js"></script>

<form ...>
    <textarea name="blah" onload="watch(this)"/>
    <input type="submit" value="Submit" />
</form>

Then watch() would register various event handlers on the element. But it seems onload only fires on elements which load resources?

What is a good pattern for allowing the HTML author to decide what elements a Javascript library will pay attention to?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Schwern
  • 153,029
  • 25
  • 195
  • 336
  • You can assign the same handler to multipe events, i.e. both an onblah and an onblubb property. And of course you shouldn't be using inline handlers anyway. – Bergi Oct 19 '16 at 03:36
  • @Bergi Yes, but that won't work for this application. It's a lot of redundancy for the user, and it hard codes which events are being watched; that is decided by the library and may change. Could you explain what the problem is with inline handlers and what the preferred alternative is? – Schwern Oct 19 '16 at 03:43
  • 1
    Have a look at [this](http://stackoverflow.com/q/6941483/1048572) – Bergi Oct 19 '16 at 04:28

2 Answers2

2

You have many options. Maybe try going with a data tag:

<textarea name="blah" data-monitored="true">

and in your JS you collect all these elements using a method like so:

var nodeList = document.querySelectorAll("[data-monitored='true']");
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
0

What's about using onfocus event handler and fire focus event on first load? Then you will manage multiply events inside this handler as you did with your watch function.

Thevs
  • 3,189
  • 2
  • 20
  • 32