javascriptfocus

JS - How to avoid a generic click handler stealing focus


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?


Solution

  • 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).