Does anyone know how to Detect Mouse Click Anywhere on Window, Not just on form?

Dani AI

Generated

Short answer for : bind a handler to the document or window instead of a specific form. If you meant clicks anywhere inside the browser page (not the OS desktop), the page-level event will catch them. is right to ask for clarification — "window" (the browser) and "form" (a DOM element) are different. 's thread about multiple forms is related when you need to ignore clicks that happen inside a particular form.

A simple, cross-browser pattern:

function anywhereClick(e) {
  e = e || window.event;
  var target = e.target || e.srcElement;
  // handle the click
}

if (document.addEventListener) {
  // use capture to catch clicks even if children call stopPropagation
  document.addEventListener('click', anywhereClick, true);
} else if (document.attachEvent) {
  // old IE fallback
  document.attachEvent('onclick', anywhereClick);
}

Notes and gotchas:

  • Use capture (third arg true) if some controls call stopPropagation() and prevent bubbling; see event bubbling and capture.
  • For immediate detection use mousedown/pointerdown instead of click (click fires after mouseup).
  • Right-clicks fire contextmenu; touch devices and pointer devices behave differently (consider pointer events for cross-device).
  • Clicks inside cross-origin iframes are not visible to the parent page. Detecting clicks outside the browser window (desktop) is not possible from a webpage for security reasons.
  • If the handler doesn't run, ensure the script runs after DOM load (place at end of body or use DOMContentLoaded). For modern uses prefer addEventListener over globals. See addEventListener for details.

Recommended Answers

All 2 Replies

So it happens we are faced with some kind of the same problem.
Look at my thread "Problem with 2 forms" maybe it helps.

But the window *IS* the form, unless you meant desktop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.