Skip to content
Advertisement

In JavaScript, is it possible save an on-click trigger and re-apply it later?

On a dynamic page I wish to disable and later re-enable sections. Visually they are grayed out, but need to prevent users from playing with the section until later.

For elements using on-click triggers, would like to:

  • save the current on-click trigger in an attribute
  • remove the current on-click trigger
  • add trigger that no-defaults and no-propagates

to re-enable:

  • get rid of the no-default trigger
  • re-apply the trigger previously saved
  • clear attribute where it was saved

From replies so far:

conjecture: using pure JavaScript html5 level, without delegation or some other external mechanism, it is impossible to extract the on-click trigger from an element.


Solution

was very tempted by delegations – and was defeated by not being able to prevent memory leaks. ended up doing it anyway, with a simple gc to do the job.

extends (add|remove)EventListener with (add|push|pop|remove)PopableEventListener, making code change trivial. allows me to push and pop listeners to any level – wonderful for form context changes other than merely enable/disable.

source: http://code.google.com/p/chess-spider/source/browse/http/scripts/popable.js

doc: http://code.google.com/p/chess-spider/wiki/PopableEventListener?ts=1303738300&updated=PopableEventListener

Editorial

Contrary to most I have seen, the ability to access listeners in the dom would be a significant benefit; besides being able to sanely disable re-enable, the ability to coerce them into a different scope would be incredibly useful.

Advertisement

Answer

The best way to handle hundreds of triggers is to use event delegation.

You then examine each click for if it matches your trigger. If it is the child of a disabled section you discard the click.

A jQuery implementation would be something like as follows:

$('.trigger', document.body).live('click', function(e) {
  var target = $(e.target);
  if (target.parents('.disabled').length > 0) {
    // handle click
  }
});

Obviously you can use other frameworks or plain JavaScript as suits you best.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement