detect-click-outside-element-in-javascript

Identifying a click outside of an HTML component is a standard procedure in web design. Whether you’re handling dropdown lists or modals (a user interface element that momentarily overlays the webpage), it’s essential to close or conceal the component when the user clicks outside of it.

In this article, you will grasp the approach to identify outside clicks using JavaScript. Additionally, you will become familiar with various optimal practices to ensure a seamless user interaction.

Table of Contents:

Grasping Event Bubbling and Capturing

Before diving into the method for detecting clicks outside an element in JavaScript, it’s crucial to comprehend how JavaScript manages events.

When you click anywhere within a webpage, the event is initially triggered for the target element where the click occurred, followed by it bubbling up to its parent element. This phenomenon is referred to as event bubbling in JavaScript. Concurrently, event capturing also transpires, where the event travels from the most superior parent to the target element. You can utilize event bubbling to identify when a user clicks outside an element.

Identifying Click Outside Element in JavaScript

JavaScript is the top choice for web development. It enables you to recognize clicks that occur outside the element through the document.addEventListener(), which is the most straightforward method for detecting external clicks.

Instance 1: Closing the dropdown when clicking outside.

Html

Code Copied!

var isMobile = window.innerWidth “);

editor76676.setValue(decodedContent); // Set the default text editor76676.clearSelection();

editor76676.setOptions({ maxLines: Infinity });

function decodeHTML76676(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard76676() { const code = editor76676.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(“.maineditor76676 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor76676 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode76676() {

var code = editor76676.getSession().getValue();

jQuery(“#runBtn76676 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type:“`html “post”,

data: { language: “html”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output76676”).html(“

"+data+"");
									jQuery(".maineditor76676 .code-editor-output").show();
									jQuery("#runBtn76676 i.run-code").hide();

} })

}

function closeoutput76676() { var code = editor76676.getSession().getValue(); jQuery(".maineditor76676 .code-editor-output").hide(); }

// Bind event listeners to the buttons document.getElementById("copyBtn76676").addEventListener("click", copyCodeToClipboard76676); document.getElementById("runBtn76676").addEventListener("click", runCode76676); document.getElementById("closeoutputBtn76676").addEventListener("click", closeoutput76676);

Result:

Mastering Click Detection Outside Elements in JavaScript

Description: This instance demonstrates that clicking a button triggers the dropdown menu (.dropdown-menu). Additionally, clicking anywhere outside of the menu dismisses it. The event.stopPropagation() prevents the click event from propagating to the document level. In summary, it is employed to halt event bubbling.

Sample 2: Dismissing a modal when clicking outside.

Html

Code Duplicated!

var isMobile = window.innerWidth ");

editor46990.setValue(decodedContent); // Set the default text editor46990.clearSelection();

editor46990.setOptions({ maxLines: Infinity });

function decodeHTML46990(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard46990() { const code = editor46990.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code duplicated to clipboard!");

jQuery(".maineditor46990 .copymessage").show(); setTimeout(function() { jQuery(".maineditor46990 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error duplicating code: ", err); }); }

function runCode46990() {

var code = editor46990.getSession().getValue();

jQuery("#runBtn46990 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "html", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output46990").html("

"+data+"");
									jQuery(".maineditor46990 .code-editor-output").show();
									jQuery("#runBtn46990 i.run-code").hide();

} })

}

function closeoutput46990() { var code = editor46990.getSession().getValue(); jQuery(".maineditor46990 .code-editor-output").hide(); }

// Bind event listeners to the buttons ``````javascript document.getElementById("copyBtn46990").addEventListener("click", copyCodeToClipboard46990); document.getElementById("runBtn46990").addEventListener("click", runCode46990); document.getElementById("closeoutputBtn46990").addEventListener("click", closeoutput46990);

Results:

Mastering Click Detection Outside Elements in JavaScript

Clarification: In this instance, you are constructing a modal utilizing the eventListeners, event.target, and the contains() function.

Recommended Practices for Detecting Clicks Outside an Element

To achieve optimal performance and enhance user experience for your project, here are several recommended practices to adhere to:

  1. Utilize stopPropagation() as Necessary
  2. Rather than attaching multiple event listeners, implement a single event listener to the document and manage several elements within it

Summary

Identifying clicks outside the HTML element is essential for constructing various UI components such as dropdowns, modals, and tooltips. JavaScript supplies you with a method to accomplish this through document.addEventListener() and event.target.contains(). By grasping these methods and acquiring knowledge of best practices, you can efficiently detect clicks outside an element.

Identifying Clicks Outside an Element in JavaScript – FAQs

Q1. How can I identify clicks outside multiple elements?

To identify clicks outside several elements, you can verify if the clicked element resides within any of the target elements using the some() and contains() functions.

Q2. How can I avoid event listeners from executing multiple times?

To stop event listeners from executing multiple times, make sure to eliminate event listeners once they are no longer necessary and refrain from adding the identical listener repeatedly within a function that executes multiple times.

Q3. Is it possible to identify clicks outside the element without utilizing JavaScript?

No, with HTML or CSS alone, you cannot detect clicks outside an element.

Q4. How can you indicate that an element is clickable?

To indicate that the element is clickable, you can apply CSS properties such as cursor: pointer or the :hover class.

Q5. What distinguishes click from onclick?

The onClick is a DOM attribute that activates a function when the button is clicked, whereas click is an event name utilized with addEventListener().

The article Identify Clicks Outside an Element in JavaScript was first published on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This