Schwern
Schwern

Reputation: 164859

Pattern for asking Javascript to pay attention to multiple element events?

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?

Upvotes: 0

Views: 49

Answers (2)

Thevs
Thevs

Reputation: 3253

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.

Upvotes: 0

user3310334
user3310334

Reputation:

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']");

Upvotes: 2

Related Questions