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.
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 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:
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!");
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:
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:
Utilize stopPropagation() as Necessary
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 HTMLelement 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 usingthe 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().
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.