Identify when a click occurs outside specific elements

I've been searching for solutions to address this issue, but so far nothing has worked. Here is the JavaScript code I am using:

var specifiedElement = document.getElementById('a');
document.addEventListener('click', function(event) {
  var isClickInside = specifiedElement.contains(event.target);
  if (!isClickInside) {
    alert('You clicked outside A and B')
  }
});
div {
  background: #aaa;
  height:2em;
  padding: 1em;
  margin-bottom:10px;
  text-align: center;
}
<div id="a">A</div>
<div id="b">B</div>

(View in JS Fiddle: https://jsfiddle.net/1zj9dmq7/)

I am trying to achieve a functionality where the "alert" function only runs when clicking outside of elements a and b, not when clicking on them directly, and without using jQuery. If anyone can assist me with this, I would greatly appreciate it. Thank you.

Answer №1

Give this a shot:

let box1 = document.getElementById('box1');
let box2 = document.getElementById('box2');

document.addEventListener('click', function(event) {
  let isClickInside = box1.contains(event.target) || box2.contains(event.target);
  if (!isClickInside) {
    alert('You clicked outside Box1 and Box2')
  }
});

Check out the live demo here: https://jsfiddle.net/1zj9dmq7/1/

Answer №2

To determine if the id matches any of the two div's ids, simply check the value of event.target.id

var specifiedElement = document.getElementById('a');
document.addEventListener('click', function(event) {
  //var isClickInside = specifiedElement.contains(event.target);
  //console.log(event.target.id);
  if ((event.target.id != 'a') && (event.target.id != 'b')) {
    alert('You clicked outside A and B')
  }
});
div {
  background: #aaa;
  height:2em;
  padding: 1em;
  margin-bottom:10px;
  text-align: center;
}
<div id="a">A</div>
<div id="b">B</div>

Answer №3

Retrieve the element's id using the event object when triggered. Show an alert if it is not 'a' or 'b'

document.addEventListener('click', function(event) {
  if (event.target.id !== 'a' && event.target.id !== 'b') {
    alert('You clicked outside A and B')
  }

});
div {
  background: #aaa;
  height: 2em;
  padding: 1em;
  margin-bottom: 10px;
  text-align: center;
}
<div id="a">A</div>
<div id="b">B</div>

Answer №4

You might want to consider using an event similar to focusLost. I believe jQuery has something along those lines, although I'm not certain of the exact name.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficiently shrink column width in Material-UI's <TableRow/> using ReactJS and Material-UI

At the moment, I am utilizing ReactJS along with Material-UI. One issue I am encountering is that when using Material-UI's <Table>, the columns' width are automatically set based on content which results in all columns having equal width. H ...

When using the resize property in monaco-editor, it may result in editor popups being obscured or

My current task involves utilizing the deltaDecorations method to display errors in my editor. Feel free to check out my code here: https://gist.github.com/dinager/41578bd658b60cc912a6023f80431810 Below is the output: I am currently attempting to in ...

"Can you explain the process by which React grabs the props using the code `const props = this.props

I recently came across an interesting article authored by Dan. The example provided in the article caught my attention: class ProfilePage extends React.Component { showMessage = (user) => { alert('Followed ' + user); }; handleClick ...

Leverage the power of Signal R through React with aspnet/signalr integration

I found a helpful resource for incorporating SignalR into react, which you can check out here. However, it seems that the code provided does not align with current standards. The @aspnet/signalr-client has been marked as obsolete and now we are required t ...

Using jQuery's .live('click') method will only bind to the initial element found on the webpage

I developed a custom jQuery plugin that attaches to 8 different elements on a webpage. Within each element, I intended to utilize the .live() method to bind a click event to a link, triggering a form submission via ajax. However, I encountered an issue whe ...

Execute a setInterval operation, pause it for a duration of 3 seconds, and then resume its execution

A setInterval function is looping through some div classes, and if it encounters a div with a specific class, it should pause for 3 seconds before resuming. I am using the following code to clear the interval: clearInterval(myInterval); However, I nee ...

Styling emails in an inbox with CSS

I am developing an email application and aiming for the inbox layout to be similar to that of Mac Mail. The emails are fetched from a database using ajax, outputting to XML. I then loop through the entries to extract the necessary elements. My concern li ...

Getting the string value from a table row using JavaScript

I need to capture the value of result_status from the row labeled status. If all values in the row labeled status are 'pass', then the result_status will also be 'pass'. However, if any one of the values in the row labeled status is &a ...

Necessitating derived classes to implement methods without making them publicly accessible

I am currently working with the following interface: import * as Bluebird from "bluebird"; import { Article } from '../../Domain/Article/Article'; export interface ITextParsingService { parsedArticle : Article; getText(uri : string) : B ...

Optimal practices for localization

Looking to translate our site into multiple languages starting with one language but planning for more in the future. Considering the most effective way to accomplish this. The plan is to use subdirectories to organize the html files, with shared files su ...

Is TypeScript being converted to JavaScript with both files in the same directory?

As I begin my journey with TypeScript in my new Angular project, I find myself pondering the best approach for organizing all these JS and TS files. Currently, it appears that the transpiler is placing the .js files in the same directory as the correspondi ...

Navigating through a sequence of URLs in Node.js, one by one

I am new to node js and experimenting with creating a web scraping script. I've received permission from the site admin to scrape their products as long as I make less than 15 requests per minute. Initially, my script was requesting all URLs at once, ...

Contrast between pm.response.json() and parsing the responseBody using JSON.parse()

Can you explain the key distinction between const json_response = pm.response.json() and json_response = JSON.parse(responseBody) ...

Console Error: Attempting to set the 'className' property of null object results in an

I'm experiencing difficulties setting up the code. The function should display all songs by a specific artist when their name is entered and the button is pressed. JavaScript file: /** * Utilizes AJAX to request data about artists from an online sou ...

Sending a POST request to a PHP file in React: A Step-by-Step Guide

Just starting out with reactjs and trying to figure out how to send an ajax request to a server (php file). Here's the structure of my project: check it out here src/index.js import React from 'react'; import ReactDOM from 'react-dom& ...

What's causing this MUI React data grid component to be rendered multiple times?

I have developed a wrapper for the MUI Data Grid Component as portrayed: Selection.tsx: import * as React from 'react'; import { DataGrid, faIR, GridSelectionModel } from '@mui/x-data-grid'; import type {} from '@mui/x-data-grid/t ...

How can the Request and Response objects be accessed in external Node.js (Express) files?

My project folder structure is as follows : app Controller testController.js Service testInfoService.js testMoreDataService.js config node-modules public index.js routes routes.js Here is some code : routes.js ro ...

Is there a way to hide my jQuery menu?

Can anyone help me figure out how to make it close when I click on a link? <nav class="navigation"> <a href="" class="menuIcon"><i class="fa fa-bars"></i></a> <ul class="nav"> <li class="clearfix"&g ...

How can I incorporate Bootstrap multi-select into the jQuery DataTables DOM?

Having trouble implementing a bootstrap multi-select inside a jQuery datatable DOM. I followed this example to add a custom element within the jQuery datatable container. It works fine for normal bootstrap select, but when trying to add a bootstrap multi-s ...

Is there a method by which I can access information from a linked document in Firebase?

I am relatively new to firebase and I am attempting to retrieve data from a referenced document in another collection to display. Link 1 Link 2 This is how I add a student and the parent's ID: const newStudent = { name: req.body.name, grade: ...