2

I am using plain JavaScript (no JQuery etc.) to display a semi-modal dialog, which contains a small FORM The way that I have things set up at the moment, the same handler will show a different dialog if the user clicks on a different part of the page, but if the user clicks on an INPUT field in my dialog, the click propogates/bubbles through to the handler, and the INPUT loses focus - the only way to type into it is to TAB into it, which is not exactly ideal!

Any suggestions on how to avoid this?

MikeB
  • 580
  • 3
  • 18

2 Answers2

2

You can attach a click handler to your dialog's main element, and stop propagation at that point:

theDialogMainElement.addEventListener("click", function(e) {
    e.stopPropagation();
}, false);

That way, clicking within the dialog doesn't propagate to the click handler on your page that's interfering.

If you need to support old versions of IE (IE8 and earlier) that don't have addEventListener and stopPropagation, see this other answer for a cross-browser event hookup function (which supplies stopPropagation as well).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This worked for me - I had initially discounted it, assuming that the focus would still be lost, but it works fine. Seems somewhat in-elegant to be doing this, but not quite as bad as trying to filter DOM elements in the 'problem' handler! – MikeB May 30 '14 at 10:44
-4

You can call a .focus() on the specific input element you are referring to. http://www.w3schools.com/jsref/met_html_focus.asp

Nxtmind
  • 57
  • 8
  • 2
    I can't vote this answer down, but I would if I could - once because it wouldn't help, and once for the link [w3fools](http://www.w3fools.com/) – MikeB May 30 '14 at 10:46